| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163 |
- #!/usr/bin/env python3
- """Create a complete CPLD analysis handoff from configured source roots."""
- from __future__ import annotations
- import json
- import hashlib
- import argparse
- import concurrent.futures
- import os
- import re
- import shutil
- import stat
- import subprocess
- import sys
- import tempfile
- import uuid
- import zipfile
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any, NamedTuple
- ROOT = Path(__file__).resolve().parent
- TOOLS = ROOT / "tools"
- if str(TOOLS) not in sys.path:
- sys.path.insert(0, str(TOOLS))
- import package_agent_handoff as handoff # noqa: E402
- import package_evidence_canon as evidence_canon # noqa: E402
- PackagingError = handoff.PackagingError
- class _IntermediateProvenanceDone(Exception):
- """Control-flow: intermediate-review provenance already materialized."""
- CONFIG_SCHEMA = "cpld-agent-analysis-sources-v1"
- DEFAULT_CONFIG = ROOT / "config" / "agent_analysis_handoff_sources.json"
- DEFAULT_OUTPUT_DIR = Path(
- os.environ.get(
- "PRODU2_HANDOFF_DIR",
- str(Path(os.environ.get("TMPDIR", "/tmp")) / "prod2u-handoff"),
- )
- )
- CONTENT_DEDUP_MIN_BYTES = 4096
- DERIVED_BOARD_VIEWER_ASSETS = frozenset(
- {
- "board-copper.svg",
- "board-silkscreen.svg",
- "board-mask-edge.svg",
- "board-copper-back.svg",
- "board-silkscreen-back.svg",
- "board-mask-edge-back.svg",
- "board-data.json",
- "build-info.json",
- "import-report.json",
- }
- )
- SELF_REFERENCE_CONTROL_FILES = (
- "HANDOFF-INDEX.json",
- "SHA256SUMS.txt",
- "EXCLUSIONS.txt",
- "PACKAGE-PURPOSE.txt",
- "START-HERE.zh-CN.md",
- "size-budget.json",
- )
- CATEGORY_ORDER = {
- "core": 0,
- "source": 0,
- "hardware": 1,
- "td-docs": 2,
- "evidence": 3,
- "meta": 4,
- }
- GENERATED_BINARY_SUFFIXES = {
- ".bit",
- ".bid",
- ".data",
- ".db",
- ".timing",
- ".rpt",
- ".area",
- ".qor",
- ".vvp",
- }
- TRANSIENT_SUFFIXES = {".pyc", ".pyo", ".tmp", ".partial", ".part", ".swp", ".swo"}
- ARCHIVE_SUFFIXES = {".zip", ".rar", ".7z", ".tgz", ".tar"}
- RUNTIME_EVIDENCE_SUFFIXES = {".log", ".logw", ".vcd", ".fst", ".lxt", ".gtkw", ".raw", ".bin"}
- BOARD_VIEWER_GENERATED_ASSETS = {
- "board-copper.svg",
- "board-silkscreen.svg",
- "board-mask-edge.svg",
- "board-copper-back.svg",
- "board-silkscreen-back.svg",
- "board-mask-edge-back.svg",
- }
- BOARD_DESIGN_SUFFIXES = {".brd", ".sch", ".kicad_pcb", ".kicad_sch", ".kicad_pro", ".kicad_prl", ".dsn"}
- IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp", ".svg"}
- STRAY_FILENAMES = {"-", "a.out"}
- REASSEMBLER_SCRIPT = '''#!/usr/bin/env python3
- """Reassemble files that were split across analysis ZIP volumes."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import shutil
- import sys
- import zipfile
- from pathlib import Path, PurePosixPath
- def safe_output_path(root: Path, relative: str) -> Path:
- portable = PurePosixPath(relative)
- if portable.is_absolute() or not portable.parts or any(part in {"", ".", ".."} for part in portable.parts):
- raise RuntimeError(f"unsafe output path: {relative}")
- target = (root / Path(*portable.parts)).resolve(strict=False)
- try:
- target.relative_to(root.resolve(strict=False))
- except ValueError as exc:
- raise RuntimeError(f"output path escapes target directory: {relative}") from exc
- return target
- def sha256_path(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--package-dir", type=Path, default=Path(__file__).resolve().parent)
- parser.add_argument("--output-dir", type=Path, default=Path("reassembled"))
- args = parser.parse_args()
- package_dir = args.package_dir.resolve(strict=True)
- output_dir = args.output_dir.resolve(strict=False)
- index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
- output_dir.mkdir(parents=True, exist_ok=True)
- for item in index.get("large_files", []):
- target = safe_output_path(output_dir, item["path"])
- target.parent.mkdir(parents=True, exist_ok=True)
- temporary = target.with_name(target.name + ".partial")
- temporary.unlink(missing_ok=True)
- total = 0
- with temporary.open("xb") as destination:
- for chunk in sorted(item["chunks"], key=lambda value: value["number"]):
- volume = package_dir / chunk["volume"]
- with zipfile.ZipFile(volume, "r") as archive:
- with archive.open(chunk["archive_path"], "r") as source:
- digest = hashlib.sha256()
- chunk_bytes = 0
- while True:
- payload = source.read(1024 * 1024)
- if not payload:
- break
- destination.write(payload)
- digest.update(payload)
- chunk_bytes += len(payload)
- if chunk_bytes != chunk["size"] or digest.hexdigest() != chunk["sha256"]:
- raise RuntimeError(f"chunk verification failed: {chunk['archive_path']}")
- total += chunk_bytes
- if total != item["size"] or sha256_path(temporary) != item["sha256"]:
- temporary.unlink(missing_ok=True)
- raise RuntimeError(f"reassembled file verification failed: {item['path']}")
- temporary.replace(target)
- print(f"reassembled: {target}")
- return 0
- if __name__ == "__main__":
- try:
- raise SystemExit(main())
- except (OSError, RuntimeError, KeyError, ValueError, json.JSONDecodeError, zipfile.BadZipFile) as exc:
- print(f"error: {exc}", file=sys.stderr)
- raise SystemExit(1)
- '''
- class ExternalSource(NamedTuple):
- id: str
- category: str
- kind: str
- path_candidates: tuple[Path, ...]
- archive_policy: str
- class HandoffConfig(NamedTuple):
- max_zip_bytes: int
- target_zip_bytes: int
- external_sources: tuple[ExternalSource, ...]
- extra_exclusions: tuple[dict[str, str], ...]
- class ResolvedSource(NamedTuple):
- id: str
- category: str
- kind: str
- path: Path
- archive_policy: str
- class PackageItem(NamedTuple):
- candidate: handoff.Candidate
- category: str
- source_id: str
- original_path: str
- scan_archive: bool
- class SourceSnapshot(NamedTuple):
- source_id: str
- root: Path
- extra_exclusions: tuple[dict[str, str], ...]
- candidates: tuple[tuple[object, ...], ...]
- excluded: tuple[tuple[str, str], ...]
- profile: str = "full"
- class AnalysisCollection(NamedTuple):
- status: str
- items: tuple[PackageItem, ...]
- excluded: tuple[dict[str, str], ...]
- warnings: tuple[dict[str, str], ...]
- sources: tuple[dict[str, object], ...]
- git: tuple[dict[str, object], ...]
- source_snapshots: tuple[SourceSnapshot, ...] = ()
- evidence_canon: dict[str, object] | None = None
- def _is_reference_path(item: PackageItem) -> bool:
- parts = item.candidate.relative.casefold().split("/")
- for index, part in enumerate(parts):
- if part == "reference":
- next_part = parts[index + 1] if index + 1 < len(parts) else ""
- if next_part == "historical":
- return False
- return True
- return False
- def _is_reference_item(item: PackageItem) -> bool:
- return item.category == "td-docs" or _is_reference_path(item)
- def _split_collection_by_reference(
- collection: AnalysisCollection,
- ) -> tuple[AnalysisCollection, AnalysisCollection]:
- core_items: list[PackageItem] = []
- reference_items: list[PackageItem] = []
- for item in collection.items:
- if _is_reference_item(item):
- if item.category == "core" and _is_reference_path(item):
- item = item._replace(category="reference")
- reference_items.append(item)
- else:
- core_items.append(item)
- reference_items_tuple = tuple(reference_items)
- core_items_tuple = tuple(core_items)
- reference_source_ids = {item.source_id for item in reference_items_tuple}
- core_source_ids = {item.source_id for item in core_items_tuple}
- def _filter_sources(
- sources: tuple[dict[str, object], ...], source_ids: set[str]
- ) -> tuple[dict[str, object], ...]:
- return tuple(s for s in sources if s.get("id") in source_ids)
- def _filter_git(
- git: tuple[dict[str, object], ...], source_ids: set[str]
- ) -> tuple[dict[str, object], ...]:
- return tuple(g for g in git if g.get("source_id") in source_ids)
- def _filter_snapshots(
- snapshots: tuple[SourceSnapshot, ...], source_ids: set[str]
- ) -> tuple[SourceSnapshot, ...]:
- return tuple(ss for ss in snapshots if ss.source_id in source_ids)
- core_collection = AnalysisCollection(
- status=collection.status,
- items=core_items_tuple,
- excluded=collection.excluded,
- warnings=collection.warnings,
- sources=_filter_sources(collection.sources, core_source_ids),
- git=_filter_git(collection.git, core_source_ids),
- source_snapshots=_filter_snapshots(collection.source_snapshots, core_source_ids),
- )
- reference_collection = AnalysisCollection(
- status=collection.status,
- items=reference_items_tuple,
- excluded=collection.excluded,
- warnings=collection.warnings,
- sources=_filter_sources(collection.sources, reference_source_ids),
- git=_filter_git(collection.git, reference_source_ids),
- source_snapshots=_filter_snapshots(collection.source_snapshots, reference_source_ids),
- )
- return core_collection, reference_collection
- class ArchivePreparation(NamedTuple):
- items: tuple[PackageItem, ...]
- excluded: tuple[dict[str, str], ...]
- warnings: tuple[dict[str, str], ...]
- def _source_snapshot(
- root: Path,
- *,
- source_id: str,
- extra_exclusions: tuple[dict[str, str], ...],
- profile: str = "full",
- ) -> SourceSnapshot:
- candidates, excluded, _ = scan_analysis_root(
- root,
- extra_exclusions=extra_exclusions,
- profile=profile,
- )
- return SourceSnapshot(
- source_id=source_id,
- root=root.resolve(strict=True),
- extra_exclusions=extra_exclusions,
- candidates=tuple(
- (
- candidate.relative,
- candidate.size,
- candidate.mtime_ns,
- candidate.device,
- candidate.inode,
- candidate.mode,
- )
- for candidate in candidates
- ),
- excluded=tuple((item["path"], item["rule"]) for item in excluded),
- profile=profile,
- )
- def _require_keys(payload: dict[str, object], allowed: set[str], label: str) -> None:
- unknown = sorted(set(payload) - allowed)
- if unknown:
- if any("include" in item.casefold() for item in unknown):
- raise PackagingError(f"positive include rules are forbidden in {label}: {unknown}")
- raise PackagingError(f"unsupported fields in {label}: {unknown}")
- def _expand_path(value: str, *, repo_root: Path, user_profile: Path) -> Path:
- tokens = {
- "repo_root": str(repo_root),
- "user_profile": str(user_profile),
- "codex_temp": str(user_profile / "CodexTemp"),
- }
- try:
- expanded = value.format_map(tokens)
- except (KeyError, ValueError) as exc:
- raise PackagingError(f"unsupported path token in external source: {value}") from exc
- return Path(expanded).expanduser()
- def load_config(
- path: Path,
- *,
- repo_root: Path = ROOT,
- user_profile: Path | None = None,
- ) -> HandoffConfig:
- try:
- payload = json.loads(path.read_text(encoding="utf-8-sig"))
- except (OSError, UnicodeError, json.JSONDecodeError) as exc:
- raise PackagingError(f"unable to read analysis source config: {path}") from exc
- if not isinstance(payload, dict):
- raise PackagingError("analysis source config must be a JSON object")
- _require_keys(
- payload,
- {
- "schema",
- "max_zip_bytes",
- "target_zip_bytes",
- "external_sources",
- "extra_exclusions",
- },
- "config",
- )
- if payload.get("schema") != CONFIG_SCHEMA:
- raise PackagingError(f"unsupported analysis source config schema: {payload.get('schema')}")
- max_zip_bytes = payload.get("max_zip_bytes")
- target_zip_bytes = payload.get("target_zip_bytes")
- if not isinstance(max_zip_bytes, int) or max_zip_bytes <= 0:
- raise PackagingError("max_zip_bytes must be a positive integer")
- if not isinstance(target_zip_bytes, int) or not 0 < target_zip_bytes < max_zip_bytes:
- raise PackagingError("target_zip_bytes must be positive and smaller than max_zip_bytes")
- raw_sources = payload.get("external_sources")
- if not isinstance(raw_sources, list):
- raise PackagingError("external_sources must be an array")
- profile = user_profile or Path.home()
- sources: list[ExternalSource] = []
- seen_ids: set[str] = set()
- for index, raw_source in enumerate(raw_sources):
- if not isinstance(raw_source, dict):
- raise PackagingError(f"external_sources[{index}] must be an object")
- _require_keys(
- raw_source,
- {"id", "category", "kind", "path_candidates", "archive_policy"},
- f"external_sources[{index}]",
- )
- source_id = raw_source.get("id")
- category = raw_source.get("category")
- kind = raw_source.get("kind")
- archive_policy = raw_source.get("archive_policy")
- raw_paths = raw_source.get("path_candidates")
- if not isinstance(source_id, str) or not source_id or source_id in seen_ids:
- raise PackagingError(f"external source id is missing or duplicated: {source_id}")
- if not isinstance(category, str) or not category:
- raise PackagingError(f"external source category is invalid: {source_id}")
- if kind not in {"directory", "file", "git_worktree"}:
- raise PackagingError(f"external source kind is invalid: {source_id}")
- if archive_policy not in {"inspect", "copy"}:
- raise PackagingError(f"external archive policy is invalid: {source_id}")
- if not isinstance(raw_paths, list) or not raw_paths or not all(isinstance(item, str) for item in raw_paths):
- raise PackagingError(f"external source path_candidates are invalid: {source_id}")
- seen_ids.add(source_id)
- sources.append(
- ExternalSource(
- id=source_id,
- category=category,
- kind=kind,
- path_candidates=tuple(
- _expand_path(item, repo_root=repo_root, user_profile=profile)
- for item in raw_paths
- ),
- archive_policy=archive_policy,
- )
- )
- raw_exclusions = payload.get("extra_exclusions")
- if not isinstance(raw_exclusions, list) or not all(isinstance(item, dict) for item in raw_exclusions):
- raise PackagingError("extra_exclusions must be an array of objects")
- exclusions: list[dict[str, str]] = []
- for index, raw_exclusion in enumerate(raw_exclusions):
- _require_keys(raw_exclusion, {"path", "reason"}, f"extra_exclusions[{index}]")
- exclusion_path = raw_exclusion.get("path")
- reason = raw_exclusion.get("reason")
- if not isinstance(exclusion_path, str) or not exclusion_path or "\\" in exclusion_path:
- raise PackagingError(f"extra exclusion path is invalid: {index}")
- if not isinstance(reason, str) or not reason.strip():
- raise PackagingError(f"extra exclusion reason is invalid: {index}")
- normalized_path = handoff.normalize_relative(exclusion_path.strip("/").split("/"))
- exclusions.append({"path": normalized_path, "reason": reason.strip()})
- return HandoffConfig(
- max_zip_bytes=max_zip_bytes,
- target_zip_bytes=target_zip_bytes,
- external_sources=tuple(sources),
- extra_exclusions=tuple(exclusions),
- )
- def analysis_exclusion_reason(
- relative: str,
- *,
- is_dir: bool,
- context: handoff.ScanContext,
- extra_exclusions: tuple[dict[str, str], ...] = (),
- profile: str = "full",
- ) -> str | None:
- del context
- lower = relative.casefold()
- parts = lower.split("/")
- raw_parts = relative.split("/")
- name = parts[-1]
- secret_reason = handoff.secret_path_reason(relative, is_dir=is_dir)
- if secret_reason:
- return secret_reason
- # Shared vendor/toolchain installer and generated-file policy (handoff common rules).
- # Critical for review-compact: root oss-cad-suite*.tgz / td_release_*.zip must never
- # enter the package and then hit fail-closed archive secret inspection.
- if not is_dir:
- common_reason = handoff.common_file_exclusion_reason(relative)
- if common_reason:
- return common_reason
- if profile == "code-only":
- for prefix, reason in handoff.CODE_ONLY_ROOT_EXCLUSIONS.items():
- if handoff.is_under(lower, prefix):
- return reason
- if not is_dir and handoff.is_under(lower, "tools/board-viewer/generated"):
- if name in handoff.CODE_ONLY_GENERATED_VISUAL_ASSETS:
- return "generated_board_viewer_visual_asset"
- if handoff.is_review_profile(profile):
- review_reason = handoff.review_exclusion_reason(
- relative, is_dir=is_dir, profile=profile
- )
- if review_reason:
- return review_reason
- for item in extra_exclusions:
- prefix = str(item.get("path", "")).casefold().strip("/")
- if prefix and handoff.is_under(lower, prefix):
- return str(item.get("reason") or "configured_analysis_exclusion")
- explicit_roots = {
- ".git": "raw_git_metadata",
- ".codegraph": "declared_external_reparse_alias",
- ".codex": "codex_session_runtime",
- ".hypothesis": "hypothesis_cache",
- ".ruff_cache": "ruff_cache",
- ".pytest_cache": "pytest_cache",
- ".chatgpt-handoff": "chatgpt_handoff_runtime_not_in_compact",
- ".playwright-upload-cache": "playwright_upload_cache",
- "dist": "generated_delivery_output",
- "log": "runtime_log_directory",
- "runs": "run_state_directory",
- "td/build": "td_build_output",
- "reference/historical": "reference_historical_material",
- "reference/original/legacy_rtl": "reference_legacy_rtl",
- "receipts/local": "local_runtime_receipt",
- # Packaged once via external source board-viewer-generated (derived evidence).
- "tools/board-viewer/generated": "board_viewer_generated_packaged_via_external_source",
- "anlogic_cd": "vendor_installer_payload",
- "node_modules": "node_modules_runtime",
- }
- for prefix, reason in explicit_roots.items():
- if handoff.is_under(lower, prefix):
- return reason
- if handoff.is_under(lower, "tmp/edge-headless-profile"):
- return "browser_runtime_profile"
- if handoff.is_under(lower, "tmp/rtl_sim"):
- return "compiled_rtl_simulation"
- if handoff.is_under(lower, "tmp/toolchain_probe"):
- return "toolchain_probe_runtime"
- if handoff.is_under(lower, "tmp/td"):
- return "td_runtime_snapshot"
- if handoff.is_under(lower, "tmp/refactor"):
- return "compiled_refactor_probe"
- if any(component.endswith("_Runs") for component in raw_parts):
- return "generated_run_directory"
- if re.match(r"^tmp/pytest-[^/]+$", lower):
- return "temporary_tool_runtime"
- if handoff.is_under(lower, "tmp"):
- return "temporary_workspace_directory"
- if handoff.is_under(lower, "td/project/log"):
- return "td_gui_runtime_log"
- if handoff.is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
- return "td_gui_runtime_run"
- if lower in {
- "td/project/.lock.f",
- "td/project/.recent_user_depot.ini",
- }:
- return "td_gui_runtime_state"
- if handoff.is_under(lower, ".git"):
- return "raw_git_metadata"
- if handoff.is_under(lower, ".omo"):
- return "agent_session_runtime"
- cache_components = {
- ".git": "raw_git_metadata",
- ".codegraph": "declared_external_reparse_alias",
- ".codex": "codex_session_runtime",
- "__pycache__": "python_bytecode_cache",
- ".pytest_cache": "pytest_cache",
- ".hypothesis": "hypothesis_cache",
- ".mypy_cache": "mypy_cache",
- ".ruff_cache": "ruff_cache",
- ".tox": "tox_environment",
- ".nox": "nox_environment",
- ".venv": "virtual_environment",
- "venv": "virtual_environment",
- "htmlcov": "coverage_report",
- "build": "build_output",
- "runs": "run_state_directory",
- "node_modules": "node_modules_runtime",
- ".playwright-browsers": "browser_runtime_cache",
- }
- for component in parts:
- if component in cache_components:
- return cache_components[component]
- if component == "dist":
- return "generated_delivery_output"
- if component.endswith(".egg-info"):
- return "python_package_metadata"
- if not is_dir:
- suffix = Path(name).suffix.casefold()
- if suffix in GENERATED_BINARY_SUFFIXES:
- return "generated_binary_artifact"
- if suffix in ARCHIVE_SUFFIXES:
- return "archive_file_not_source"
- if suffix in RUNTIME_EVIDENCE_SUFFIXES:
- return "runtime_evidence_or_waveform"
- if suffix in BOARD_DESIGN_SUFFIXES:
- if handoff.is_board_viewer_fixture_path(relative):
- return None
- if handoff.is_review_profile(profile):
- return "heavy_design_original_not_packaged"
- if "reference" in parts:
- return None
- return "board_design_file"
- if suffix in IMAGE_SUFFIXES:
- if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
- return None
- if handoff.is_board_viewer_fixture_path(relative):
- return None
- if handoff.is_review_profile(profile) and suffix == ".pdf":
- return "heavy_design_original_not_packaged"
- if "reference" in parts:
- return None
- return "image_file"
- if name in STRAY_FILENAMES:
- return "stray_or_temporary_file"
- if suffix in TRANSIENT_SUFFIXES or name.endswith("~"):
- return "temporary_file"
- if suffix == ".dmp" or name.startswith("minidump-"):
- return "crash_dump"
- if name in {".ds_store", "thumbs.db", "desktop.ini"}:
- return "os_metadata_cache"
- return None
- def scan_analysis_root(
- root: Path,
- *,
- extra_exclusions: tuple[dict[str, str], ...] = (),
- profile: str = "full",
- ) -> tuple[list[handoff.Candidate], list[dict[str, str]], handoff.ScanContext]:
- def resolve(relative: str, *, is_dir: bool, context: handoff.ScanContext) -> str | None:
- return analysis_exclusion_reason(
- relative,
- is_dir=is_dir,
- context=context,
- extra_exclusions=extra_exclusions,
- profile=profile,
- )
- return handoff.scan_tree(root, exclusion_resolver=resolve, profile=profile)
- def resolve_external_sources(
- sources: tuple[ExternalSource, ...],
- ) -> tuple[list[ResolvedSource], list[dict[str, str]]]:
- resolved: list[ResolvedSource] = []
- warnings: list[dict[str, str]] = []
- for source in sources:
- selected: Path | None = None
- for candidate in source.path_candidates:
- if source.kind == "file" and candidate.is_file():
- selected = candidate.resolve(strict=True)
- break
- if source.kind in {"directory", "git_worktree"} and candidate.is_dir():
- selected = candidate.resolve(strict=True)
- break
- if selected is None:
- warnings.append(
- {
- "code": "missing_external_source",
- "source_id": source.id,
- "message": "no configured path candidate is available",
- }
- )
- continue
- resolved.append(
- ResolvedSource(
- id=source.id,
- category=source.category,
- kind=source.kind,
- path=selected,
- archive_policy=source.archive_policy,
- )
- )
- return resolved, warnings
- def _candidate_from_path(path: Path, relative: str) -> handoff.Candidate:
- try:
- file_stat = os.lstat(path)
- except OSError as exc:
- raise PackagingError(f"unable to inspect generated analysis input: {relative}") from exc
- if not stat.S_ISREG(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
- raise PackagingError(f"analysis input is not a regular file: {relative}")
- return handoff.Candidate(
- absolute=path,
- relative=handoff.normalize_relative(relative.split("/")),
- size=file_stat.st_size,
- mtime_ns=file_stat.st_mtime_ns,
- device=int(file_stat.st_dev),
- inode=int(file_stat.st_ino),
- mode=int(file_stat.st_mode),
- )
- def make_package_item(
- path: Path,
- *,
- relative: str,
- category: str,
- source_id: str,
- scan_archive: bool = True,
- ) -> PackageItem:
- return PackageItem(
- candidate=_candidate_from_path(path, relative),
- category=category,
- source_id=source_id,
- original_path=path.name,
- scan_archive=scan_archive,
- )
- def _rebase_candidate(candidate: handoff.Candidate, prefix: str) -> handoff.Candidate:
- return handoff.Candidate(
- absolute=candidate.absolute,
- relative=handoff.normalize_relative([*prefix.split("/"), *candidate.relative.split("/")]),
- size=candidate.size,
- mtime_ns=candidate.mtime_ns,
- device=candidate.device,
- inode=candidate.inode,
- mode=candidate.mode,
- )
- def _rebase_exclusions(excluded: list[dict[str, str]], prefix: str) -> list[dict[str, str]]:
- return [
- {
- "path": handoff.normalize_relative([*prefix.split("/"), *item["path"].split("/")]),
- "rule": item["rule"],
- }
- for item in excluded
- ]
- def _collect_directory_items(
- *,
- root: Path,
- source_id: str,
- category: str,
- prefix: str,
- extra_exclusions: tuple[dict[str, str], ...],
- profile: str = "full",
- ) -> tuple[list[PackageItem], list[dict[str, str]]]:
- candidates, excluded, _ = scan_analysis_root(
- root,
- extra_exclusions=extra_exclusions,
- profile=profile,
- )
- items = [
- PackageItem(
- candidate=_rebase_candidate(candidate, prefix),
- category=category,
- source_id=source_id,
- original_path=candidate.relative,
- scan_archive=True,
- )
- for candidate in candidates
- ]
- return items, _rebase_exclusions(excluded, prefix)
- def _resolve_delivery_commit(root: Path, binding_commit: str | None) -> str:
- """Resolve exact DELIVERY commit for review source snapshot."""
- if binding_commit:
- text = binding_commit.strip().casefold()
- if not re.fullmatch(r"[0-9a-f]{40}", text):
- raise PackagingError(f"invalid binding_commit: {binding_commit!r}")
- return text
- # Fail closed before git-archive: gitless roots must not produce a package.
- if not handoff.live_git_cli_usable(root):
- raise PackagingError(
- "review package requires live Git provenance "
- "(HEAD/branch/status/log-20/tree/source-file-sha256); "
- "got status='not_a_git_worktree'. "
- "Package from an exact DELIVERY Git worktree/repo — "
- "sanitized-snapshot-status alone is not sufficient."
- )
- git = shutil.which("git")
- if not git:
- raise PackagingError(
- "review package requires live Git provenance; git binary unavailable"
- )
- try:
- completed = subprocess.run(
- [git, "rev-parse", "HEAD"],
- cwd=root,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=60,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired) as exc:
- raise PackagingError(
- "review package requires live Git provenance; "
- "unable to resolve DELIVERY commit via git rev-parse"
- ) from exc
- head = completed.stdout.strip().casefold()
- if completed.returncode != 0 or not re.fullmatch(r"[0-9a-f]{40}", head):
- raise PackagingError(
- "review package requires live Git provenance; "
- "unable to resolve DELIVERY commit via git rev-parse: "
- + (completed.stderr or completed.stdout or "unknown error").strip()[:300]
- )
- return head
- def _collect_exact_commit_unified_items(
- *,
- root: Path,
- commit: str,
- source_id: str,
- temp_root: Path,
- extra_exclusions: tuple[dict[str, str], ...],
- profile: str,
- ) -> tuple[list[PackageItem], list[dict[str, str]], dict[str, object]]:
- """Build unified source/evidence items from exact DELIVERY tracked tree only.
- Never walks a dirty post-test worktree. Applies the same review exclusion
- policy to the commit export, then remaps into source/ or evidence/.
- """
- git = shutil.which("git")
- if not git:
- raise PackagingError("git required for exact_commit_tracked_subset source snapshot")
- export_root = temp_root / f"exact-commit-source-{commit[:12]}"
- if export_root.exists():
- shutil.rmtree(export_root)
- export_root.mkdir(parents=True, exist_ok=True)
- tar_path = temp_root / f"exact-commit-source-{commit[:12]}.tar"
- try:
- completed = subprocess.run(
- [git, "archive", "--format=tar", "-o", str(tar_path), commit],
- cwd=root,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=600,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired) as exc:
- raise PackagingError(f"git archive {commit} failed for source snapshot") from exc
- if completed.returncode != 0 or not tar_path.is_file():
- detail = (completed.stdout or "").strip().splitlines()
- suffix = f": {detail[-1]}" if detail else ""
- raise PackagingError(f"git archive {commit} failed for source snapshot{suffix}")
- import tarfile
- with tarfile.open(tar_path, "r:") as archive:
- try:
- archive.extractall(export_root, filter="data")
- except TypeError:
- archive.extractall(export_root)
- # Enumerate every tracked path (pre-exclusion) for packaged-source-manifest.
- tracked_all: list[str] = []
- for path in sorted(export_root.rglob("*")):
- if path.is_file():
- tracked_all.append(path.relative_to(export_root).as_posix())
- root_items, root_excluded = _collect_directory_items(
- root=export_root,
- source_id=source_id,
- category="source",
- prefix="__workspace__",
- extra_exclusions=extra_exclusions,
- profile=profile,
- )
- remapped: list[PackageItem] = []
- included_tracked: list[dict[str, object]] = []
- for item in root_items:
- original = item.original_path
- package_relative, category = _package_relative_for_unified(
- source_id=source_id,
- original_relative=original,
- profile=profile,
- )
- remapped.append(
- PackageItem(
- candidate=handoff.Candidate(
- absolute=item.candidate.absolute,
- relative=package_relative,
- size=item.candidate.size,
- mtime_ns=item.candidate.mtime_ns,
- device=item.candidate.device,
- inode=item.candidate.inode,
- mode=item.candidate.mode,
- ),
- category=category,
- source_id=source_id,
- original_path=original,
- scan_archive=item.scan_archive,
- )
- )
- if original in _SOFTWARE_MIRROR_UNDER_SOURCE and not package_relative.startswith(
- "source/"
- ):
- mirror_relative = f"source/{original}"
- remapped.append(
- PackageItem(
- candidate=handoff.Candidate(
- absolute=item.candidate.absolute,
- relative=mirror_relative,
- size=item.candidate.size,
- mtime_ns=item.candidate.mtime_ns,
- device=item.candidate.device,
- inode=item.candidate.inode,
- mode=item.candidate.mode,
- ),
- category="source",
- source_id=source_id,
- original_path=original,
- scan_archive=item.scan_archive,
- )
- )
- included_tracked.append(
- {
- "path": original,
- "package_path": mirror_relative,
- "size": item.candidate.size,
- "sha256": handoff.sha256_file(item.candidate.absolute),
- }
- )
- if package_relative.startswith("source/"):
- included_tracked.append(
- {
- "path": original,
- "package_path": package_relative,
- "size": item.candidate.size,
- "sha256": handoff.sha256_file(item.candidate.absolute),
- }
- )
- excluded: list[dict[str, str]] = []
- policy_excluded: list[dict[str, str]] = []
- for entry in root_excluded:
- original_excluded = entry["path"]
- if original_excluded.startswith("__workspace__/"):
- original_excluded = original_excluded[len("__workspace__/") :]
- elif original_excluded == "__workspace__":
- original_excluded = "."
- package_relative, _category = _package_relative_for_unified(
- source_id=source_id,
- original_relative=original_excluded,
- profile=profile,
- )
- row = {
- "path": (
- original_excluded if original_excluded == "." else package_relative
- ),
- "rule": entry["rule"],
- }
- excluded.append(row)
- if original_excluded != ".":
- policy_excluded.append(
- {"path": original_excluded, "rule": entry["rule"]}
- )
- included_paths = {str(row["path"]) for row in included_tracked}
- evidence_mapped = sorted(
- {
- item.original_path
- for item in remapped
- if item.candidate.relative.startswith("evidence/")
- }
- )
- evidence_set = set(evidence_mapped)
- # Re-resolve exclusion per tracked file so directory-level skips are explicit.
- scan_context = handoff.load_scan_context(export_root, profile=profile)
- resolve = handoff.make_exclusion_resolver(profile)
- def _file_exclusion_reason(rel: str) -> str | None:
- # Prefer analysis_exclusion_reason (extra_exclusions + profile).
- reason = analysis_exclusion_reason(
- rel,
- is_dir=False,
- context=scan_context,
- extra_exclusions=extra_exclusions,
- profile=profile,
- )
- if reason:
- return reason
- # Directory ancestors excluded by scan (e.g. reference/original).
- parts = rel.split("/")
- for idx in range(len(parts) - 1, 0, -1):
- parent = "/".join(parts[:idx])
- parent_reason = analysis_exclusion_reason(
- parent,
- is_dir=True,
- context=scan_context,
- extra_exclusions=extra_exclusions,
- profile=profile,
- )
- if parent_reason:
- return parent_reason
- # Fallback shared resolver (defensive).
- return resolve(rel, is_dir=False, context=scan_context)
- per_file_excluded: list[dict[str, str]] = []
- silent_missing: list[str] = []
- for path in tracked_all:
- if path in included_paths or path in evidence_set:
- continue
- reason = _file_exclusion_reason(path)
- if reason:
- per_file_excluded.append({"path": path, "rule": reason})
- else:
- silent_missing.append(path)
- # Prefer compact directory-level exclusion rows; enrich with per-file reasons.
- policy_by_path = {row["path"]: row["rule"] for row in policy_excluded}
- for row in per_file_excluded:
- policy_by_path.setdefault(row["path"], row["rule"])
- policy_excluded_final = [
- {"path": path, "rule": rule}
- for path, rule in sorted(policy_by_path.items(), key=lambda pair: pair[0].casefold())
- ]
- manifest: dict[str, object] = {
- "schema": "prod2u-packaged-source-manifest-v1",
- "source_snapshot_mode": "exact_commit_tracked_subset",
- "delivery_commit": commit,
- "tracked_file_count": len(tracked_all),
- "included_source_count": len(included_tracked),
- "included_source_files": sorted(
- included_tracked, key=lambda row: str(row["path"]).casefold()
- ),
- "policy_excluded": policy_excluded_final,
- "evidence_mapped_tracked": evidence_mapped,
- "silent_missing_tracked": silent_missing,
- "note": (
- "source/ members are exact DELIVERY git-archive tracked files after "
- "review-compact exclusion policy; never a dirty post-test worktree scan."
- ),
- }
- if silent_missing:
- raise PackagingError(
- "exact commit source snapshot has tracked files neither packaged nor "
- f"policy-excluded: {silent_missing[:8]}"
- )
- return remapped, excluded, manifest
- def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
- try:
- completed = subprocess.run(
- command,
- cwd=cwd,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=timeout,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired) as exc:
- raise PackagingError(f"unable to run Git for {cwd.name}") from exc
- if completed.returncode != 0:
- detail = completed.stdout.strip().splitlines()
- suffix = f": {detail[-1]}" if detail else ""
- raise PackagingError(f"Git command failed for {cwd.name}{suffix}")
- return completed.stdout
- def _is_evidence_source_path(relative: str) -> bool:
- lower = relative.casefold()
- if evidence_canon.workspace_canonical_path(relative) is not None:
- return True
- if handoff.is_under(lower, "receipts"):
- return True
- if handoff.is_under(lower, "tools/board-viewer/generated"):
- return True
- name = lower.rsplit("/", 1)[-1]
- if name in DERIVED_BOARD_VIEWER_ASSETS and "board-viewer" in lower:
- return True
- return False
- def _unified_item_placement(
- *,
- source_id: str,
- original_relative: str,
- profile: str,
- ) -> tuple[str, str]:
- """Return (package_relative_or_prefix, category) for unified review layouts.
- When the workspace path matches the compact evidence allowlist, the first
- element is the full canonical package path (not merely a directory prefix).
- """
- del profile
- if source_id == "board-viewer-generated" or source_id.startswith("board-viewer"):
- return "evidence/board-viewer", "evidence"
- canon = evidence_canon.workspace_canonical_path(original_relative)
- if canon is not None and source_id in {"workspace-current", "source"}:
- return canon, "evidence"
- if source_id != "workspace-current" and source_id != "source":
- if _is_evidence_source_path(original_relative):
- return f"evidence/external/{source_id}", "evidence"
- return f"source/external/{source_id}", "source"
- if _is_evidence_source_path(original_relative):
- return "evidence", "evidence"
- return "source", "source"
- def _unified_layout_prefix(
- *,
- source_id: str,
- original_relative: str,
- profile: str,
- ) -> tuple[str, str]:
- """Compatibility wrapper: directory prefix + category for unified layouts."""
- placed, category = _unified_item_placement(
- source_id=source_id,
- original_relative=original_relative,
- profile=profile,
- )
- if placed.startswith("evidence/") and placed.count("/") >= 2 and not placed.endswith("/"):
- # Full canonical path — expose parent as prefix for exclusion rewriting.
- if evidence_canon.workspace_canonical_path(original_relative) == placed:
- parent = placed.rsplit("/", 1)[0]
- return parent, category
- return placed, category
- def _package_relative_for_unified(
- *,
- source_id: str,
- original_relative: str,
- profile: str,
- ) -> tuple[str, str]:
- placed, category = _unified_item_placement(
- source_id=source_id,
- original_relative=original_relative,
- profile=profile,
- )
- if evidence_canon.workspace_canonical_path(original_relative) == placed:
- return placed, category
- if original_relative in {".", ""}:
- return placed, category
- return f"{placed}/{original_relative}", category
- # Workspace paths remapped into evidence/ that must also remain under source/ for
- # detached software replay and active markdown relative links. Physical duplicates
- # under evidence/ are intentional review entry points; content dedup must not drop
- # the source/ copy (see apply_content_dedup software-source guard).
- _SOFTWARE_MIRROR_UNDER_SOURCE = frozenset(
- {
- "config/source_closure.json",
- "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
- "docs/HARDWARE_BRINGUP_NOTES.zh-CN.md",
- }
- )
- _STALE_EMBEDDED_COMPACT_SELFTEST = "evidence/selftest/compact-package-selftest.json"
- _COMPACT_SELFTEST_POINTER = "evidence/selftest/compact-package-selftest-pointer.json"
- def _materialize_bytes_items(
- payloads: dict[str, bytes],
- *,
- temp_root: Path,
- source_id: str,
- category: str,
- ) -> list[PackageItem]:
- items: list[PackageItem] = []
- root = temp_root / "generated-meta"
- root.mkdir(parents=True, exist_ok=True)
- for relative, payload in sorted(payloads.items()):
- path = root / Path(*relative.split("/"))
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_bytes(payload)
- items.append(
- make_package_item(
- path,
- relative=relative,
- category=category,
- source_id=source_id,
- scan_archive=False,
- )
- )
- return items
- def _create_git_bundle(
- *,
- root: Path,
- source_id: str,
- temp_root: Path,
- ) -> tuple[PackageItem, dict[str, object]]:
- git = shutil.which("git")
- if not git:
- raise PackagingError("Git is required to create complete analysis history bundles")
- bundle_dir = temp_root / "git-bundles"
- bundle_dir.mkdir(parents=True, exist_ok=True)
- bundle_path = bundle_dir / f"{source_id}.bundle"
- _run_git([git, "bundle", "create", str(bundle_path), "--all"], cwd=root)
- verify_output = _run_git([git, "bundle", "verify", str(bundle_path)], cwd=root)
- head = _run_git([git, "rev-parse", "HEAD"], cwd=root).strip()
- branch = _run_git([git, "branch", "--show-current"], cwd=root).strip() or None
- status = _run_git(
- [
- git,
- "--no-optional-locks",
- "-c",
- "core.fsmonitor=false",
- "-c",
- "core.untrackedCache=false",
- "status",
- "--short",
- "--branch",
- "--untracked-files=all",
- ],
- cwd=root,
- )
- ref_lines = [line for line in verify_output.splitlines() if " refs/" in line or line.rstrip().endswith(" HEAD")]
- candidate = _candidate_from_path(bundle_path, f"git-history/{source_id}.bundle")
- item = PackageItem(
- candidate=candidate,
- category="core",
- source_id=source_id,
- original_path=".git",
- scan_archive=False,
- )
- metadata = {
- "source_id": source_id,
- "branch": branch,
- "head": head,
- "working_tree_clean": not any(
- line and not line.startswith("##") for line in status.splitlines()
- ),
- "status": "pass",
- "bundle_path": candidate.relative,
- "bundle_ref_count": len(ref_lines),
- "bundle_verify": "pass",
- }
- return item, metadata
- def collect_analysis_inputs(
- *,
- repo_root: Path,
- config: HandoffConfig,
- temp_root: Path,
- include_git_bundle: bool = True,
- profile: str = "full",
- include_sanitized_git_snapshot: bool = False,
- package_name: str = "pending",
- evidence_root: Path | None = None,
- include_process_evidence: bool = False,
- bitstream_path: Path | None = None,
- td_report_paths: list[Path] | None = None,
- binding_commit: str | None = None,
- require_bitstream_binding: bool = False,
- package_stage: str = "intermediate-review",
- ) -> AnalysisCollection:
- root = repo_root.resolve(strict=True)
- temp_root.mkdir(parents=True, exist_ok=True)
- if profile not in handoff.HANDOFF_PROFILES:
- raise PackagingError(f"unsupported handoff profile: {profile}")
- if profile == "full" and not include_git_bundle:
- raise PackagingError(
- "full inclusion-first packages require a git bundle so replay can restore "
- "commit-to-commit source closure comparison"
- )
- unified = handoff.uses_unified_layout(profile)
- # review-compact / review-debug never ship a full bundle unless explicitly forced later.
- if profile in {"review-compact", "review-debug"}:
- include_git_bundle = False
- items: list[PackageItem] = []
- excluded: list[dict[str, str]] = []
- warnings: list[dict[str, str]] = []
- sources: list[dict[str, object]] = []
- git_metadata: list[dict[str, object]] = []
- source_snapshots: list[SourceSnapshot] = []
- primary_source_id = "workspace-current"
- packaged_source_manifest: dict[str, object] | None = None
- if unified and profile in {"review-compact", "review-debug"}:
- # Exact DELIVERY tracked-only snapshot — never scan a dirty post-test WT.
- delivery_commit = _resolve_delivery_commit(root, binding_commit)
- remapped, root_excluded, packaged_source_manifest = (
- _collect_exact_commit_unified_items(
- root=root,
- commit=delivery_commit,
- source_id=primary_source_id,
- temp_root=temp_root / "exact-commit-source",
- extra_exclusions=config.extra_exclusions,
- profile=profile,
- )
- )
- items.extend(remapped)
- excluded.extend(root_excluded)
- elif unified:
- # Collect with a temporary prefix, then remap into source/ or evidence/.
- root_items, root_excluded = _collect_directory_items(
- root=root,
- source_id=primary_source_id,
- category="source",
- prefix="__workspace__",
- extra_exclusions=config.extra_exclusions,
- profile=profile,
- )
- remapped: list[PackageItem] = []
- for item in root_items:
- original = item.original_path
- package_relative, category = _package_relative_for_unified(
- source_id=primary_source_id,
- original_relative=original,
- profile=profile,
- )
- remapped.append(
- PackageItem(
- candidate=handoff.Candidate(
- absolute=item.candidate.absolute,
- relative=package_relative,
- size=item.candidate.size,
- mtime_ns=item.candidate.mtime_ns,
- device=item.candidate.device,
- inode=item.candidate.inode,
- mode=item.candidate.mode,
- ),
- category=category,
- source_id=primary_source_id,
- original_path=original,
- scan_archive=item.scan_archive,
- )
- )
- if original in _SOFTWARE_MIRROR_UNDER_SOURCE and not package_relative.startswith(
- "source/"
- ):
- remapped.append(
- PackageItem(
- candidate=handoff.Candidate(
- absolute=item.candidate.absolute,
- relative=f"source/{original}",
- size=item.candidate.size,
- mtime_ns=item.candidate.mtime_ns,
- device=item.candidate.device,
- inode=item.candidate.inode,
- mode=item.candidate.mode,
- ),
- category="source",
- source_id=primary_source_id,
- original_path=original,
- scan_archive=item.scan_archive,
- )
- )
- items.extend(remapped)
- for entry in root_excluded:
- original_excluded = entry["path"]
- if original_excluded.startswith("__workspace__/"):
- original_excluded = original_excluded[len("__workspace__/") :]
- elif original_excluded == "__workspace__":
- original_excluded = "."
- package_relative, _category = _package_relative_for_unified(
- source_id=primary_source_id,
- original_relative=original_excluded,
- profile=profile,
- )
- excluded.append(
- {
- "path": (
- original_excluded
- if original_excluded == "."
- else package_relative
- ),
- "rule": entry["rule"],
- }
- )
- else:
- root_items, root_excluded = _collect_directory_items(
- root=root,
- source_id=primary_source_id,
- category="core",
- prefix="workspace-current",
- extra_exclusions=config.extra_exclusions,
- profile=profile,
- )
- items.extend(root_items)
- excluded.extend(root_excluded)
- source_snapshots.append(
- _source_snapshot(
- root,
- source_id=primary_source_id,
- extra_exclusions=config.extra_exclusions,
- profile=profile,
- )
- )
- sources.append(
- {
- "id": primary_source_id,
- "category": "source" if unified else "core",
- "kind": (
- "exact_commit_tracked_subset"
- if packaged_source_manifest is not None
- else "git_worktree"
- ),
- "path": str(root),
- "status": "pass",
- "source_snapshot_mode": (
- packaged_source_manifest.get("source_snapshot_mode")
- if packaged_source_manifest is not None
- else "worktree_scan"
- ),
- "delivery_commit": (
- packaged_source_manifest.get("delivery_commit")
- if packaged_source_manifest is not None
- else None
- ),
- }
- )
- if include_git_bundle:
- bundle_item, bundle_metadata = _create_git_bundle(
- root=root,
- source_id=primary_source_id,
- temp_root=temp_root,
- )
- if unified:
- # Keep bundle under meta/git-history for archive-local.
- bundle_rel = f"meta/git-history/{primary_source_id}.bundle"
- bundle_item = PackageItem(
- candidate=handoff.Candidate(
- absolute=bundle_item.candidate.absolute,
- relative=bundle_rel,
- size=bundle_item.candidate.size,
- mtime_ns=bundle_item.candidate.mtime_ns,
- device=bundle_item.candidate.device,
- inode=bundle_item.candidate.inode,
- mode=bundle_item.candidate.mode,
- ),
- category="meta",
- source_id=primary_source_id,
- original_path=".git",
- scan_archive=False,
- )
- bundle_metadata = {**bundle_metadata, "bundle_path": bundle_rel}
- items.append(bundle_item)
- git_metadata.append(bundle_metadata)
- elif unified:
- # review-* must collect live Git provenance (linked worktrees OK via git CLI).
- # Fail closed: never ship a "success" package with only sanitized-snapshot-status.
- stage_for_clean = str(package_stage or "intermediate-review").strip().casefold().replace(
- "_", "-"
- )
- if stage_for_clean in {"intermediate", "non-final"}:
- stage_for_clean = "intermediate-review"
- elif stage_for_clean in {"final", "final-review"}:
- stage_for_clean = "final-review"
- provenance, provenance_artifacts = handoff.collect_review_git_provenance(
- root,
- include_sanitized_git_snapshot=include_sanitized_git_snapshot,
- meta_prefix="meta/git",
- temp_root=temp_root / "review-git",
- # Final-review: porcelain must be empty including untracked (clean worktree).
- # Intermediate unit/fixture packs keep tracked-only dirty gate.
- require_clean=(profile == "review-compact"),
- require_clean_untracked=(
- profile == "review-compact" and stage_for_clean == "final-review"
- ),
- commit=binding_commit,
- )
- if profile in {"review-compact", "review-debug"}:
- prov_status = str(provenance.get("status") or "")
- if prov_status != "pass":
- raise PackagingError(
- "review package requires live Git provenance "
- f"(HEAD/branch/status/log-20/tree/source-file-sha256); "
- f"got status={prov_status!r}. "
- "Package from an exact DELIVERY Git worktree/repo — "
- "sanitized-snapshot-status alone is not sufficient."
- )
- prov_failures = handoff.validate_review_git_provenance_artifacts(
- provenance_artifacts,
- meta_prefix="meta/git",
- expected_head=str(provenance.get("head") or "") or None,
- )
- if prov_failures:
- raise PackagingError(
- "review Git provenance artifacts incomplete/inconsistent: "
- + ", ".join(prov_failures)
- )
- binding = handoff.build_td_source_closure_binding(
- root,
- bitstream_path=bitstream_path,
- td_report_paths=td_report_paths,
- evidence_root=evidence_root,
- commit=binding_commit or str(provenance.get("head") or "") or None,
- require_bitstream=require_bitstream_binding,
- )
- binding_bytes = handoff.json_bytes(binding)
- # Canonical path meta/td/...; keep legacy flat alias for older consumers.
- provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
- provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
- stage_n = str(package_stage or "final-review").strip().casefold().replace("_", "-")
- if stage_n in {"intermediate", "intermediate-review", "non-final"}:
- stage_n = "intermediate-review"
- elif stage_n in {"final", "final-review"}:
- stage_n = "final-review"
- else:
- raise PackagingError(
- f"unsupported package_stage={package_stage!r}; "
- "use intermediate-review or final-review"
- )
- purpose = handoff.package_purpose_text(
- profile, package_name=package_name, package_stage=stage_n
- )
- provenance_artifacts["meta/PACKAGE-PURPOSE.txt"] = purpose.encode("utf-8")
- provenance_artifacts["meta/package-stage.txt"] = (stage_n + "\n").encode("utf-8")
- # Minimal provenance: REFERENCE-POINTER + source-closure-relations + sibling stub.
- # release_set_id must match firmware package inputs (no cyclic ZIP SHAs).
- try:
- import package_provenance as pkg_prov
- from build_firmware_package import motor_polarity_config_identity
- bitstream_obj = binding.get("bitstream") if isinstance(binding.get("bitstream"), dict) else {}
- head = str(provenance.get("head") or "")
- # Load TD report early: ARTIFACT-SOURCE is the production-input tip from
- # the bound TD report (or canonical ARTIFACT_DEFAULT), NOT delivery HEAD.
- from build_firmware_package import ( # noqa: WPS433
- OLD_BASELINE_COMMIT_DEFAULT,
- generate_source_closure_comparison,
- )
- td_report_payload: dict[str, Any] | None = None
- for report_meta in binding.get("td_reports") or []:
- if not isinstance(report_meta, dict):
- continue
- report_path = Path(str(report_meta.get("path") or ""))
- if report_path.is_file():
- try:
- td_report_payload = json.loads(
- report_path.read_text(encoding="utf-8-sig")
- )
- except (OSError, json.JSONDecodeError):
- continue
- if td_report_payload.get("synthesis_input_manifest", {}).get("inputs"):
- break
- td_report_payload = None
- if td_report_payload is None:
- for candidate in td_report_paths or []:
- cpath = Path(str(candidate))
- if cpath.is_file():
- try:
- td_report_payload = json.loads(
- cpath.read_text(encoding="utf-8-sig")
- )
- except (OSError, json.JSONDecodeError):
- continue
- if td_report_payload.get("synthesis_input_manifest", {}).get(
- "inputs"
- ):
- break
- td_report_payload = None
- if td_report_payload is None:
- if stage_n != "intermediate-review":
- raise PackagingError(
- "final-review source-closure relations require a TD report with "
- "synthesis_input_manifest.inputs (pass --td-report)"
- )
- # Intermediate: emit non-final provenance without pretending TD closed.
- delivery = str(head or binding_commit or "").strip()
- if not delivery:
- raise PackagingError(
- "intermediate-review delivery commit unavailable "
- "(git head and --binding-commit both empty)"
- )
- artifact = delivery
- ref_pointer = pkg_prov.build_reference_pointer(
- artifact_commit=artifact,
- delivery_commit=delivery,
- reference_changed=False,
- reference_reused=True,
- repo_root=root,
- summary_only=False,
- )
- relations = pkg_prov.build_source_closure_relations(
- old_baseline_commit=pkg_prov.BASE_DEV_COMMIT_DEFAULT,
- artifact_commit=artifact,
- delivery_commit=delivery,
- old_to_artifact_unchanged=None,
- artifact_to_delivery_unchanged=True,
- old_to_artifact_changed_paths=[],
- artifact_to_delivery_changed_paths=[],
- comparison_mode="comparison_unavailable",
- )
- sibling = pkg_prov.sibling_role_stub(
- role="review-compact",
- expected_filename=pkg_prov.release_sibling_filename(
- "firmware", delivery
- ),
- release_set_id=f"intermediate-nonfinal-{delivery[:8]}",
- )
- polarity = motor_polarity_config_identity(root)
- release_identity = {
- "schema": "prod2u-release-set-identity-v1",
- "algorithm_version": "prod2u-release-set-id-v1",
- "package_stage": "intermediate-review",
- "non_final": True,
- "release_set_id": f"intermediate-nonfinal-{delivery[:8]}",
- "base_dev_commit": pkg_prov.BASE_DEV_COMMIT_DEFAULT,
- "artifact_source_commit": artifact,
- "delivery_commit": delivery,
- "bitstream_sha256": None,
- "production_polarity_config": {
- "limit_active_high": polarity.get("limit_active_high"),
- "dir_close_level": polarity.get("dir_close_level"),
- "close_limit_is_ls": polarity.get("close_limit_is_ls"),
- "generated_masks": polarity.get("generated_masks")
- or polarity.get("masks"),
- "config_fingerprint": polarity.get("sha256"),
- },
- "verification_run_id": None,
- "td_artifact_run_id": None,
- "td_receipt_sha256": None,
- "reference_set_fingerprint": pkg_prov.reference_set_fingerprint(root)[
- "sha256"
- ],
- "hardware_validation": "not_run",
- "note": (
- "INTERMEDIATE / NON-FINAL review package. No fresh TD/bitstream "
- "closure. Do not treat as final release set."
- ),
- }
- provenance_artifacts["meta/REFERENCE-POINTER.json"] = handoff.json_bytes(
- ref_pointer
- )
- provenance_artifacts["meta/source-closure-relations.json"] = (
- handoff.json_bytes(relations)
- )
- provenance_artifacts["meta/release-set-sibling.json"] = handoff.json_bytes(
- sibling
- )
- provenance_artifacts["meta/release-set-identity.json"] = (
- handoff.json_bytes(release_identity)
- )
- provenance_artifacts["meta/release-set-id.txt"] = (
- f"intermediate-nonfinal-{delivery[:8]}\n"
- ).encode("ascii")
- if packaged_source_manifest is not None:
- provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
- handoff.json_bytes(packaged_source_manifest)
- )
- raise _IntermediateProvenanceDone()
- report_artifact = str(
- td_report_payload.get("commit_full")
- or td_report_payload.get("commit")
- or ""
- )
- # DELIVERY is the package tip (git HEAD / --binding-commit). Never fall
- # back to ARTIFACT or sibling filenames collapse to the wrong tip.
- delivery = str(head or binding_commit or "").strip()
- artifact = str(
- binding.get("artifact_source_commit")
- or report_artifact
- or pkg_prov.ARTIFACT_DEFAULT
- or ""
- ).strip()
- if not delivery:
- raise PackagingError(
- "review-compact delivery commit unavailable "
- "(git head and --binding-commit both empty)"
- )
- if not artifact:
- raise PackagingError(
- "review-compact artifact_source_commit unavailable "
- "(TD report commit / ARTIFACT_DEFAULT missing)"
- )
- # Prefer TD production tip when binder incorrectly equates ARTIFACT to DELIVERY.
- if report_artifact and artifact == delivery and report_artifact != delivery:
- artifact = report_artifact
- ref_pointer = pkg_prov.build_reference_pointer(
- artifact_commit=artifact,
- delivery_commit=delivery,
- reference_changed=False,
- reference_reused=True,
- repo_root=root,
- summary_only=False,
- )
- bit_sha = str(
- binding.get("bitstream_sha256")
- or bitstream_obj.get("sha256")
- or td_report_payload.get("bitstream_sha256")
- or ""
- )
- # Config fingerprint is motor-polarity masks, not project_config_sha256.
- config_fp = motor_polarity_config_identity(root)["sha256"]
- td_run = str(
- binding.get("td_run_id")
- or binding.get("run_id")
- or td_report_payload.get("run_id")
- or td_report_payload.get("td_run_id")
- or ""
- )
- ref_fp = pkg_prov.reference_set_fingerprint(root)
- if not bit_sha:
- raise PackagingError("release_set_id requires bound bitstream sha256")
- if not td_run:
- raise PackagingError("release_set_id requires td run_id from bound receipt")
- release_set_id = pkg_prov.compute_release_set_id(
- artifact_commit=artifact,
- delivery_commit=delivery,
- bitstream_sha256=bit_sha,
- config_fingerprint=config_fp,
- td_run_id=td_run,
- reference_set_fingerprint_sha256=ref_fp["sha256"],
- )
- art_to_del = generate_source_closure_comparison(
- td_report=td_report_payload,
- artifact_commit=artifact,
- matrix_commit=artifact,
- final_dev_commit=delivery,
- repo_root=root,
- )
- old_to_art = generate_source_closure_comparison(
- td_report=td_report_payload,
- artifact_commit=OLD_BASELINE_COMMIT_DEFAULT,
- matrix_commit=OLD_BASELINE_COMMIT_DEFAULT,
- final_dev_commit=artifact,
- repo_root=root,
- )
- comparison_mode = str(art_to_del.get("mode") or "commit_compare")
- if comparison_mode == "comparison_unavailable_without_git":
- relations = pkg_prov.build_source_closure_relations(
- old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
- artifact_commit=artifact,
- delivery_commit=delivery,
- old_to_artifact_unchanged=None,
- artifact_to_delivery_unchanged=None,
- old_to_artifact_changed_paths=[],
- artifact_to_delivery_changed_paths=[],
- comparison_mode="comparison_unavailable",
- )
- else:
- relations = pkg_prov.build_source_closure_relations(
- old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
- artifact_commit=artifact,
- delivery_commit=delivery,
- old_to_artifact_unchanged=bool(
- old_to_art.get("source_closure_equal")
- ),
- artifact_to_delivery_unchanged=bool(
- art_to_del.get("source_closure_equal")
- ),
- old_to_artifact_changed_paths=list(
- old_to_art.get("production_changed_paths") or []
- ),
- artifact_to_delivery_changed_paths=list(
- art_to_del.get("production_changed_paths") or []
- ),
- comparison_mode=comparison_mode,
- )
- rel_check = pkg_prov.validate_source_closure_relations(relations)
- if rel_check["status"] != "pass":
- raise PackagingError(
- f"source-closure relations inconsistent: {rel_check['failures']}"
- )
- # Explicit dual-commit fields (keep commit_full for compatibility).
- binding["artifact_source_commit"] = artifact
- binding["delivery_commit"] = delivery
- binding["artifact_to_delivery_unchanged"] = bool(
- art_to_del.get("source_closure_equal")
- )
- binding["td_run_id"] = td_run
- if binding.get("commit_full") in {None, "", artifact} and delivery:
- binding["commit_full"] = delivery
- binding["commit_short"] = delivery[:8]
- # Re-encode binding after enriching identity fields.
- binding_bytes = handoff.json_bytes(binding)
- provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
- provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
- provenance_artifacts["meta/SOURCE-CLOSURE-COMPARISON-ART-TO-DEL.json"] = (
- handoff.json_bytes(art_to_del)
- )
- provenance_artifacts["meta/SOURCE-CLOSURE-COMPARISON-OLD-TO-ART.json"] = (
- handoff.json_bytes(old_to_art)
- )
- sibling = pkg_prov.sibling_role_stub(
- role="review-compact",
- expected_filename=pkg_prov.release_sibling_filename("firmware", delivery),
- release_set_id=release_set_id,
- )
- provenance_artifacts["meta/REFERENCE-POINTER.json"] = handoff.json_bytes(ref_pointer)
- provenance_artifacts["meta/source-closure-relations.json"] = handoff.json_bytes(
- relations
- )
- provenance_artifacts["meta/release-set-sibling.json"] = handoff.json_bytes(sibling)
- provenance_artifacts["meta/release-set-id.txt"] = (release_set_id + "\n").encode(
- "ascii"
- )
- # Dual run-id semantics: TD verification vs TD artifact workspace.
- # release_set_id already binds td_run (= TD receipt run_id / artifact run).
- td_verification_run_id = str(
- binding.get("verification_run_id")
- or td_report_payload.get("verification_run_id")
- or ""
- )
- td_artifact_run_id = str(
- binding.get("td_artifact_run_id")
- or td_report_payload.get("td_artifact_run_id")
- or td_report_payload.get("artifact_run_id")
- or td_report_payload.get("run_id")
- or td_run
- or ""
- )
- if not td_artifact_run_id:
- # Recover from known receipt path shape .../runs/<id>/...
- for report_meta in binding.get("td_reports") or []:
- if not isinstance(report_meta, dict):
- continue
- report_path = str(report_meta.get("path") or "")
- marker = "/runs/"
- if marker in report_path.replace("\\", "/"):
- part = report_path.replace("\\", "/").split(marker, 1)[1]
- td_artifact_run_id = part.split("/", 1)[0]
- break
- if not td_artifact_run_id:
- raise PackagingError(
- "final-review requires td_artifact_run_id from bound TD receipt "
- "(no hardcoded historical fallback)"
- )
- if td_artifact_run_id == "20260806T112210Z-3f2f5f2f":
- raise PackagingError(
- "refusing Round-10 hardcoded td_artifact_run_id fallback "
- "20260806T112210Z-3f2f5f2f"
- )
- binding["verification_run_id"] = td_verification_run_id or td_run
- binding["td_artifact_run_id"] = td_artifact_run_id
- binding["td_run_id_semantics"] = {
- "verification_run_id": td_verification_run_id or td_run,
- "td_artifact_run_id": td_artifact_run_id,
- "release_set_id_uses": "td_artifact_run_id",
- }
- binding_bytes = handoff.json_bytes(binding)
- provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
- provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
- polarity = motor_polarity_config_identity(root)
- release_identity = {
- "schema": "prod2u-release-set-identity-v1",
- "algorithm_version": "prod2u-release-set-id-v1",
- "package_stage": stage_n,
- "non_final": stage_n != "final-review",
- "release_set_id": release_set_id,
- "base_dev_commit": pkg_prov.BASE_DEV_COMMIT_DEFAULT,
- "artifact_source_commit": artifact,
- "delivery_commit": delivery,
- "bitstream_sha256": bit_sha,
- "production_polarity_config": {
- "limit_active_high": polarity.get("limit_active_high"),
- "dir_close_level": polarity.get("dir_close_level"),
- "close_limit_is_ls": polarity.get("close_limit_is_ls"),
- "generated_masks": polarity.get("generated_masks")
- or polarity.get("masks"),
- "config_fingerprint": config_fp,
- },
- "verification_run_id": td_verification_run_id or td_run,
- "td_artifact_run_id": td_artifact_run_id,
- "td_receipt_sha256": None,
- "reference_fingerprint_schema": ref_fp.get("schema"),
- "reference_set_fingerprint": ref_fp["sha256"],
- "hardware_validation": "not_run",
- "note": (
- "release_set_id is independently recomputable from these fields; "
- "td_artifact_run_id (TD receipt run_id) feeds release_set_id; "
- "verification_run_id is the separate TD verification id. "
- "Sibling ZIP SHAs live only in the external release-set JSON."
- ),
- }
- for report_meta in binding.get("td_reports") or []:
- if isinstance(report_meta, dict) and report_meta.get("sha256"):
- release_identity["td_receipt_sha256"] = report_meta.get("sha256")
- break
- provenance_artifacts["meta/release-set-identity.json"] = handoff.json_bytes(
- release_identity
- )
- if packaged_source_manifest is not None:
- provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
- handoff.json_bytes(packaged_source_manifest)
- )
- except _IntermediateProvenanceDone:
- pass
- except Exception as exc: # noqa: BLE001 - surface helper failure in meta, fail later selftest
- provenance_artifacts["meta/REFERENCE-POINTER-ERROR.txt"] = (
- f"reference pointer build failed: {exc}\n"
- ).encode("utf-8")
- # Even when provenance helpers fail, still emit packaged-source-manifest if built.
- if (
- packaged_source_manifest is not None
- and "meta/git/packaged-source-manifest.json" not in provenance_artifacts
- ):
- provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
- handoff.json_bytes(packaged_source_manifest)
- )
- # External selftest sidecar certifies the final ZIP; never embed a recursive
- # compact-package-selftest.json that claims to authenticate this archive.
- delivery_short = str(provenance.get("head") or binding_commit or "unknown")[:8]
- provenance_artifacts[_COMPACT_SELFTEST_POINTER] = handoff.json_bytes(
- {
- "schema": "cpld-review-compact-selftest-pointer-v1",
- "role": "external_sidecar_only",
- "expected_external_selftest_filename": (
- f"prod2u-review-compact-door-percent-{delivery_short}.selftest.json"
- ),
- "note": (
- "Final review ZIP SHA / member_count are certified only by the "
- "external sibling selftest sidecar listed above. This archive does "
- "not embed compact-package-selftest.json (avoids cyclic self-hash)."
- ),
- }
- )
- items.extend(
- _materialize_bytes_items(
- provenance_artifacts,
- temp_root=temp_root,
- source_id="meta-generated",
- category="meta",
- )
- )
- git_metadata.append(
- {
- "source_id": primary_source_id,
- "status": provenance.get("status"),
- "branch": provenance.get("branch"),
- "head": provenance.get("head"),
- "full_bundle": False,
- "provenance": provenance,
- "td_source_closure_binding": binding,
- }
- )
- resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
- if profile == "code-only":
- resolved_sources = [
- source for source in resolved_sources if source.id != "board-viewer-generated"
- ]
- warnings.extend(source_warnings)
- for source in resolved_sources:
- if unified:
- # Prefer derived board-viewer assets under evidence/.
- if source.kind == "file":
- prefix, category = _unified_layout_prefix(
- source_id=source.id,
- original_relative=source.path.name,
- profile=profile,
- )
- candidate = _candidate_from_path(
- source.path, f"{prefix}/{source.path.name}"
- )
- items.append(
- PackageItem(
- candidate=candidate,
- category=category,
- source_id=source.id,
- original_path=source.path.name,
- scan_archive=source.archive_policy == "inspect",
- )
- )
- else:
- source_items, source_excluded = _collect_directory_items(
- root=source.path,
- source_id=source.id,
- category="evidence",
- prefix="__external__",
- extra_exclusions=config.extra_exclusions,
- profile=profile,
- )
- for item in source_items:
- original = item.original_path
- prefix, category = _unified_layout_prefix(
- source_id=source.id,
- original_relative=original,
- profile=profile,
- )
- items.append(
- PackageItem(
- candidate=_rebase_candidate(
- handoff.Candidate(
- absolute=item.candidate.absolute,
- relative=original,
- size=item.candidate.size,
- mtime_ns=item.candidate.mtime_ns,
- device=item.candidate.device,
- inode=item.candidate.inode,
- mode=item.candidate.mode,
- ),
- prefix,
- ),
- category=category,
- source_id=source.id,
- original_path=original,
- scan_archive=item.scan_archive,
- )
- )
- for entry in source_excluded:
- original_excluded = entry["path"]
- if original_excluded.startswith("__external__/"):
- original_excluded = original_excluded[len("__external__/") :]
- prefix, _category = _unified_layout_prefix(
- source_id=source.id,
- original_relative=original_excluded,
- profile=profile,
- )
- excluded.append(
- {
- "path": f"{prefix}/{original_excluded}",
- "rule": entry["rule"],
- }
- )
- source_snapshots.append(
- _source_snapshot(
- source.path,
- source_id=source.id,
- extra_exclusions=config.extra_exclusions,
- profile=profile,
- )
- )
- else:
- prefix = f"external/{source.id}"
- if source.kind == "file":
- candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
- items.append(
- PackageItem(
- candidate=candidate,
- category=source.category,
- source_id=source.id,
- original_path=source.path.name,
- scan_archive=source.archive_policy == "inspect",
- )
- )
- else:
- source_items, source_excluded = _collect_directory_items(
- root=source.path,
- source_id=source.id,
- category=source.category,
- prefix=prefix,
- extra_exclusions=config.extra_exclusions,
- profile=profile,
- )
- items.extend(source_items)
- excluded.extend(source_excluded)
- source_snapshots.append(
- _source_snapshot(
- source.path,
- source_id=source.id,
- extra_exclusions=config.extra_exclusions,
- profile=profile,
- )
- )
- sources.append(
- {
- "id": source.id,
- "category": "evidence" if unified else source.category,
- "kind": source.kind,
- "path": str(source.path),
- "status": "pass",
- }
- )
- if source.kind == "git_worktree" and include_git_bundle:
- external_bundle, external_git = _create_git_bundle(
- root=source.path,
- source_id=source.id,
- temp_root=temp_root,
- )
- items.append(external_bundle)
- git_metadata.append(external_git)
- evidence_canon_fields: dict[str, object] | None = None
- include_process = include_process_evidence or profile == "review-debug"
- if unified:
- if evidence_root is not None:
- staged = evidence_canon.stage_evidence_root(
- evidence_root,
- staging_root=temp_root / "canonical-evidence",
- include_process_evidence=include_process,
- )
- for staged_file in staged.staged:
- items.append(
- PackageItem(
- candidate=_candidate_from_path(
- staged_file.absolute,
- staged_file.relative,
- ),
- category="evidence",
- source_id="evidence-root",
- original_path=staged_file.original_path,
- scan_archive=False,
- )
- )
- excluded.extend(staged.excluded)
- sources.append(
- {
- "id": "evidence-root",
- "category": "evidence",
- "kind": "directory",
- "path": str(evidence_root.resolve()),
- "status": "pass",
- }
- )
- evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
- catalog=staged.catalog,
- aliases=staged.aliases,
- log_policy_actions=staged.log_policy_actions,
- include_process_evidence=include_process,
- profile=profile,
- )
- kept_items, filter_excluded, _remaps = evidence_canon.filter_package_items_for_compact(
- items,
- profile=profile,
- include_process_evidence=include_process,
- )
- items = list(kept_items)
- excluded.extend(filter_excluded)
- # Workspace allowlist remaps + evidence-root staging can both land on the
- # same canonical evidence/ path; keep one physical copy (prefer evidence-root).
- deduped: dict[str, PackageItem] = {}
- for item in items:
- key = handoff.windows_collision_key(item.candidate.relative)
- previous = deduped.get(key)
- if previous is None:
- deduped[key] = item
- continue
- prefer_new = item.source_id == "evidence-root" and previous.source_id != "evidence-root"
- keep, drop = (item, previous) if prefer_new else (previous, item)
- deduped[key] = keep
- excluded.append(
- {
- "path": drop.original_path or drop.candidate.relative,
- "rule": "canonical_path_physical_dedup",
- }
- )
- if evidence_canon_fields is not None:
- aliases = list(evidence_canon_fields.get("aliases") or [])
- aliases.append(
- {
- "physical_path": keep.candidate.relative,
- "logical_paths": [
- f"evidence/from/{drop.original_path or drop.candidate.relative}"
- ],
- "reason": "canonical_path_physical_dedup",
- }
- )
- evidence_canon_fields["aliases"] = aliases
- items = list(deduped.values())
- if evidence_canon_fields is None:
- evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
- catalog=[
- {
- "key": key,
- "canonical_path": evidence_canon.load_allowlist().by_key[key].canonical_path,
- "role": "compact_default",
- "source_original": None,
- }
- for key in evidence_canon.compact_default_key_list()
- ],
- aliases=[],
- log_policy_actions=[],
- include_process_evidence=include_process,
- profile=profile,
- )
- # Record workspace allowlisted evidence that survived filtering.
- present = {item.candidate.relative.casefold() for item in items}
- catalog = list(evidence_canon_fields.get("catalog", [])) # type: ignore[arg-type]
- allowlist = evidence_canon.load_allowlist()
- for entry in allowlist.canonical_entries:
- if entry.canonical_path.casefold() in present and not any(
- str(row.get("canonical_path", "")).casefold() == entry.canonical_path.casefold()
- for row in catalog
- ):
- catalog.append(
- {
- "key": entry.key,
- "canonical_path": entry.canonical_path,
- "role": "compact_default",
- "source_original": "workspace",
- }
- )
- evidence_canon_fields["catalog"] = sorted(catalog, key=lambda row: str(row["key"]))
- evidence_canon_fields["compact_default_keys"] = sorted(
- {str(row["key"]) for row in catalog if row.get("role") == "compact_default"}
- )
- # Drop any stale embedded final-ZIP selftest receipt (recursive hash hazard).
- filtered_items: list[PackageItem] = []
- for item in items:
- rel = item.candidate.relative.replace("\\", "/")
- if rel == _STALE_EMBEDDED_COMPACT_SELFTEST or rel.endswith(
- "/" + _STALE_EMBEDDED_COMPACT_SELFTEST
- ):
- excluded.append(
- {
- "path": item.original_path or rel,
- "rule": "stale_embedded_compact_selftest_forbidden",
- }
- )
- continue
- if rel.rsplit("/", 1)[-1].casefold() == "compact-package-selftest.json":
- excluded.append(
- {
- "path": item.original_path or rel,
- "rule": "stale_embedded_compact_selftest_forbidden",
- }
- )
- continue
- filtered_items.append(item)
- items = filtered_items
- items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
- excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
- return AnalysisCollection(
- status="pass_with_warnings" if warnings else "pass",
- items=tuple(items),
- excluded=tuple(excluded),
- warnings=tuple(warnings),
- sources=tuple(sources),
- git=tuple(git_metadata),
- source_snapshots=tuple(source_snapshots),
- evidence_canon=evidence_canon_fields,
- )
- def find_7z() -> Path | None:
- discovered = shutil.which("7z") or shutil.which("7zz")
- candidates = [
- Path(discovered) if discovered else None,
- Path(r"C:\Program Files\7-Zip\7z.exe"),
- Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
- ]
- for candidate in candidates:
- if candidate is not None and candidate.is_file():
- return candidate.resolve(strict=True)
- return None
- def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
- del staging_root
- return [
- "a",
- "-tzip",
- "-mm=Deflate",
- "-mx=9",
- "-mmt",
- "-y",
- "-r",
- str(archive_path),
- "CPLD\\*",
- ]
- def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
- try:
- completed = subprocess.run(
- [str(seven_zip), *arguments],
- cwd=cwd,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=300,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired) as exc:
- raise PackagingError("unable to run 7-Zip for archive inspection") from exc
- if completed.returncode != 0:
- detail = completed.stdout.strip().splitlines()
- suffix = f": {detail[-1]}" if detail else ""
- raise PackagingError(f"7-Zip archive inspection failed{suffix}")
- return completed.stdout
- def _rename_archive_entries(
- seven_zip: Path,
- archive_path: Path,
- renames: list[tuple[str, str]],
- ) -> None:
- for offset in range(0, len(renames), 64):
- batch = renames[offset : offset + 64]
- arguments = ["rn", "-y", str(archive_path)]
- for old_name, new_name in batch:
- arguments.extend((old_name, new_name))
- _run_7z(seven_zip, arguments, cwd=archive_path.parent)
- def _parse_7z_members(payload: str, archive_label: str) -> list[dict[str, str]]:
- in_members = False
- current: dict[str, str] = {}
- members: list[dict[str, str]] = []
- for raw_line in payload.splitlines():
- line = raw_line.rstrip("\r\n")
- if line.strip() == "----------":
- in_members = True
- current = {}
- continue
- if not in_members:
- continue
- if not line.strip():
- if current:
- members.append(current)
- current = {}
- continue
- key, separator, value = line.partition(" = ")
- if separator:
- current[key.strip()] = value.strip()
- if current:
- members.append(current)
- for member in members:
- raw_path = member.get("Path", "")
- normalized = raw_path.replace("\\", "/")
- if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
- raise PackagingError(f"unsafe archive member path in {archive_label}")
- handoff.normalize_relative(normalized.split("/"))
- if member.get("Encrypted") not in {None, "", "-"}:
- raise PackagingError(f"encrypted archive member is unsupported in {archive_label}")
- if member.get("Symbolic Link") or member.get("Hard Link"):
- raise PackagingError(f"archive link member is unsupported in {archive_label}")
- if member.get("Alternate Stream") not in {None, "", "-"}:
- raise PackagingError(f"archive alternate stream is unsupported in {archive_label}")
- if member.get("Split Before") not in {None, "", "-"} or member.get("Split After") not in {
- None,
- "",
- "-",
- }:
- raise PackagingError(f"split archive member is unsupported in {archive_label}")
- return members
- def _inspect_and_extract_unsupported_archive(
- item: PackageItem,
- *,
- temp_root: Path,
- seven_zip: Path,
- extra_exclusions: tuple[dict[str, str], ...],
- ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
- listing = _run_7z(
- seven_zip,
- ["l", "-slt", "-sccUTF-8", str(item.candidate.absolute)],
- cwd=item.candidate.absolute.parent,
- )
- members = _parse_7z_members(listing, item.candidate.relative)
- file_members = [
- member
- for member in members
- if member.get("Folder") != "+" and "D" not in member.get("Attributes", "")
- ]
- expected_bytes = sum(int(member.get("Size") or "0") for member in file_members)
- token = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
- extract_root = temp_root / "expanded-archives" / token
- extract_root.mkdir(parents=True, exist_ok=False)
- _run_7z(
- seven_zip,
- ["x", "-y", "-aoa", "-sccUTF-8", f"-o{extract_root}", str(item.candidate.absolute)],
- cwd=item.candidate.absolute.parent,
- )
- actual_files = [path for path in extract_root.rglob("*") if path.is_file()]
- actual_bytes = sum(path.stat().st_size for path in actual_files)
- if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
- raise PackagingError(
- f"archive extraction inventory mismatch: {item.candidate.relative} "
- f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
- )
- expanded_candidates, expanded_excluded, _ = scan_analysis_root(
- extract_root,
- extra_exclusions=extra_exclusions,
- )
- handoff.audit_candidates(expanded_candidates)
- expanded_prefix = f"{item.candidate.relative}.expanded"
- expanded_items = [
- PackageItem(
- candidate=_rebase_candidate(candidate, expanded_prefix),
- category=item.category,
- source_id=item.source_id,
- original_path=f"{item.original_path}!/{candidate.relative}",
- scan_archive=True,
- )
- for candidate in expanded_candidates
- ]
- rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
- sensitive_rules = {
- "credential_or_license_file",
- "credential_configuration_file",
- "private_key_file",
- "secret_environment_file",
- "cloud_credential_file",
- "container_registry_credential_file",
- }
- contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
- return expanded_items, rebased_excluded, contains_sensitive
- def _inspect_and_extract_zip_archive(
- item: PackageItem,
- *,
- temp_root: Path,
- extra_exclusions: tuple[dict[str, str], ...],
- ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
- archive_label = item.candidate.relative
- try:
- with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
- file_members: list[zipfile.ZipInfo] = []
- expected_bytes = 0
- for info in archive.infolist():
- normalized = info.filename.replace("\\", "/")
- if (
- not normalized
- or normalized.startswith("/")
- or re.match(r"^[A-Za-z]:", normalized)
- ):
- raise PackagingError(
- f"unsafe archive member path in {archive_label}"
- )
- handoff.normalize_relative(normalized.split("/"))
- if info.flag_bits & 0x1:
- raise PackagingError(
- f"encrypted archive member is unsupported in {archive_label}"
- )
- member_mode = (info.external_attr >> 16) & 0xFFFF
- member_type = stat.S_IFMT(member_mode)
- if info.is_dir():
- if (
- info.file_size != 0
- or info.compress_size != 0
- or member_type not in {0, stat.S_IFDIR}
- ):
- raise PackagingError(
- f"unsafe archive member type in {archive_label}"
- )
- continue
- if member_type not in {0, stat.S_IFREG}:
- raise PackagingError(
- f"unsafe archive member type in {archive_label}"
- )
- file_members.append(info)
- expected_bytes += info.file_size
- except (OSError, zipfile.BadZipFile) as exc:
- raise PackagingError(
- f"unable to inspect source archive: {archive_label}"
- ) from exc
- token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
- extract_root = temp_root / "expanded-archives" / token
- extract_root.mkdir(parents=True, exist_ok=False)
- actual_files: list[Path] = []
- actual_bytes = 0
- try:
- with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
- for info in file_members:
- parts = info.filename.replace("\\", "/").split("/")
- target_path = extract_root / Path(*parts)
- target_path.parent.mkdir(parents=True, exist_ok=True)
- with archive.open(info, "r") as source, target_path.open("wb") as destination:
- shutil.copyfileobj(source, destination, length=1024 * 1024)
- actual_files.append(target_path)
- actual_bytes += target_path.stat().st_size
- except (OSError, zipfile.BadZipFile) as exc:
- raise PackagingError(
- f"unable to extract source archive: {archive_label}"
- ) from exc
- if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
- raise PackagingError(
- f"archive extraction inventory mismatch: {archive_label} "
- f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
- )
- expanded_candidates, expanded_excluded, _ = scan_analysis_root(
- extract_root,
- extra_exclusions=extra_exclusions,
- )
- handoff.audit_candidates(expanded_candidates)
- expanded_prefix = f"{archive_label}.expanded"
- expanded_items = [
- PackageItem(
- candidate=_rebase_candidate(candidate, expanded_prefix),
- category=item.category,
- source_id=item.source_id,
- original_path=f"{item.original_path}!/{candidate.relative}",
- scan_archive=True,
- )
- for candidate in expanded_candidates
- ]
- rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
- sensitive_rules = {
- "credential_or_license_file",
- "credential_configuration_file",
- "private_key_file",
- "secret_environment_file",
- "cloud_credential_file",
- "container_registry_credential_file",
- }
- contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
- return expanded_items, rebased_excluded, contains_sensitive
- def prepare_unsupported_archives(
- items: tuple[PackageItem, ...],
- *,
- temp_root: Path,
- seven_zip: Path | None,
- extra_exclusions: tuple[dict[str, str], ...],
- ) -> ArchivePreparation:
- prepared: list[PackageItem] = []
- excluded: list[dict[str, str]] = []
- warnings: list[dict[str, str]] = []
- temp_root.mkdir(parents=True, exist_ok=True)
- for item in items:
- archive_kind = handoff.archive_kind(item.candidate.relative)
- if archive_kind is None:
- prepared.append(item)
- continue
- if archive_kind == "zip":
- expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
- item,
- temp_root=temp_root,
- extra_exclusions=extra_exclusions,
- )
- elif seven_zip is None:
- if _is_reference_item(item):
- warnings.append(
- {
- "code": "unsupported_archive_without_7zip",
- "source_id": item.source_id,
- "path": item.candidate.relative,
- "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
- }
- )
- prepared.append(item._replace(scan_archive=False))
- continue
- if item.candidate.absolute.is_file():
- raise PackagingError(
- "7-Zip is required to inspect unsupported source archives"
- )
- prepared.append(item._replace(scan_archive=False))
- continue
- else:
- expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
- item,
- temp_root=temp_root,
- seven_zip=seven_zip,
- extra_exclusions=extra_exclusions,
- )
- has_filtered_members = bool(expanded_excluded)
- if has_filtered_members:
- prepared.extend(expanded_items)
- excluded.extend(expanded_excluded)
- if contains_sensitive:
- excluded.append(
- {
- "path": item.candidate.relative,
- "rule": "unsupported_archive_contains_sensitive_content",
- }
- )
- elif has_filtered_members:
- excluded.append(
- {
- "path": item.candidate.relative,
- "rule": "archive_contains_excluded_members",
- }
- )
- else:
- prepared.append(item._replace(scan_archive=archive_kind != "unsupported"))
- prepared.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
- excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
- return ArchivePreparation(
- items=tuple(prepared),
- excluded=tuple(excluded),
- warnings=tuple(warnings),
- )
- def _utc_now() -> str:
- return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
- def _validate_package_name(package_name: str) -> None:
- try:
- collision_key = handoff.windows_collision_key(package_name)
- except PackagingError as exc:
- raise PackagingError("package name is not a portable Windows file name") from exc
- if (
- not handoff.SAFE_PACKAGE_NAME.fullmatch(package_name)
- or package_name in {".", ".."}
- or not collision_key
- ):
- raise PackagingError("package name is not a portable Windows file name")
- def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
- return (
- CATEGORY_ORDER.get(item.category, len(CATEGORY_ORDER)),
- item.category.casefold(),
- handoff.windows_collision_key(item.candidate.relative),
- )
- def _path_basename(relative: str) -> str:
- return relative.casefold().rsplit("/", 1)[-1]
- def _is_board_viewer_generated_path(relative: str) -> bool:
- lower = relative.casefold()
- return (
- "board-viewer-generated" in lower
- or handoff.is_under(lower, "evidence/board-viewer")
- or "/tools/board-viewer/generated/" in f"/{lower}/"
- or lower.startswith("tools/board-viewer/generated/")
- )
- def _is_reference_original_path(relative: str) -> bool:
- lower = f"/{relative.casefold()}/"
- return "/reference/original/" in lower or lower.startswith("/reference/original/")
- def _dedup_canonical_path(paths: list[str]) -> str:
- # Prefer compact evidence allowlist canonical paths first (P4).
- try:
- preferred = evidence_canon.prefer_canonical_path(paths)
- if evidence_canon.is_compact_allowlisted(preferred):
- return preferred
- except ValueError:
- pass
- def rank(path: str) -> tuple[int, int, str]:
- name = _path_basename(path)
- in_reference = _is_reference_original_path(path)
- in_generated = _is_board_viewer_generated_path(path)
- if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
- return (0 if in_generated else 1, 0 if in_reference else 1, path.casefold())
- if name.endswith((".brd", ".pdf", ".dsn", ".sch")):
- return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
- return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
- return sorted(paths, key=rank)[0]
- def _is_software_source_package_path(relative: str) -> bool:
- """Tracked software under source/ must keep its canonical path (no content-dedup drop)."""
- lower = relative.casefold()
- if not lower.startswith("source/"):
- return False
- # Derived board-viewer / heavy design originals should not live under source/
- # in review-compact; if they do, still protect software extensions.
- name = _path_basename(relative)
- if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf", ".dsn")):
- return False
- return True
- def _should_content_dedup(size: int, relative: str) -> bool:
- # Never content-dedup tracked software under source/. A generated SBY/workdir
- # copy with identical bytes must not replace the authoritative source path.
- lower = relative.casefold()
- if _is_software_source_package_path(relative):
- return False
- # Finalize layout requires both canonical and legacy git SHA maps as physical members.
- base = _path_basename(relative)
- if base in {"source-file-sha256.json", "file-sha256.json"} and "/meta/git/" in f"/{lower}":
- return False
- name = base
- if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf")):
- return True
- if evidence_canon.is_compact_allowlisted(relative):
- return True
- return size >= CONTENT_DEDUP_MIN_BYTES
- def apply_content_dedup(
- items: tuple[PackageItem, ...],
- inventory: list[dict[str, object]],
- ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], list[dict[str, str]]]:
- """Keep one physical copy per identical content hash; record logical aliases.
- Content dedup is only for evidence aliases / board-viewer / heavy originals /
- large non-source twins. Authoritative ``source/`` software is never grouped
- (see ``_should_content_dedup``), so generated workdir copies cannot replace it.
- """
- by_path = {str(row["path"]): row for row in inventory}
- groups: dict[str, list[PackageItem]] = {}
- for item in items:
- row = by_path[item.candidate.relative]
- sha = str(row["sha256"])
- size = int(row["size"])
- if not _should_content_dedup(size, item.candidate.relative):
- continue
- groups.setdefault(sha, []).append(item)
- drop_paths: set[str] = set()
- dedup_records: list[dict[str, object]] = []
- excluded: list[dict[str, str]] = []
- for sha, group in sorted(groups.items(), key=lambda pair: pair[0]):
- if len(group) < 2:
- continue
- paths = [item.candidate.relative for item in group]
- canonical = _dedup_canonical_path(paths)
- aliases = sorted(path for path in paths if path != canonical)
- # Absolute guard: never drop software source even if mis-grouped.
- aliases = [path for path in aliases if not _is_software_source_package_path(path)]
- if not aliases:
- continue
- if _is_software_source_package_path(canonical):
- # Prefer keeping software source as physical; aliases are non-source.
- pass
- size = int(by_path[canonical]["size"])
- dedup_records.append(
- {
- "sha256": sha,
- "size": size,
- "physical_path": canonical,
- "logical_paths": aliases,
- "reason": "identical_content_single_physical_copy",
- }
- )
- for alias in aliases:
- drop_paths.add(alias)
- excluded.append(
- {
- "path": alias,
- "rule": "duplicate_content_logical_alias",
- }
- )
- physical_items = tuple(
- item for item in items if item.candidate.relative not in drop_paths
- )
- dedup_records.sort(key=lambda row: str(row["physical_path"]).casefold())
- excluded.sort(key=lambda row: handoff.windows_collision_key(row["path"]))
- return physical_items, dedup_records, excluded
- def classify_derived_evidence(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
- derived: list[dict[str, object]] = []
- for item in items:
- name = _path_basename(item.candidate.relative)
- if name not in DERIVED_BOARD_VIEWER_ASSETS:
- continue
- if not _is_board_viewer_generated_path(item.candidate.relative):
- continue
- role = "derived_from_brd_visual" if name in BOARD_VIEWER_GENERATED_ASSETS else "derived_from_brd_parsed"
- derived.append(
- {
- "path": item.candidate.relative,
- "asset": name,
- "role": role,
- "authority": "analysis_evidence_not_source_closure",
- "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
- }
- )
- derived.sort(key=lambda row: str(row["path"]).casefold())
- return derived
- def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[str, object]:
- """Extract a published package and verify SHA256SUMS plus inventory hashes.
- Returns package-content verification plus the four-state replay skeleton:
- ``package_content_replay``, ``detached_software_replay`` (not_run here),
- ``reference_regeneration_replay=not_packaged_by_policy``,
- ``hardware_validation=not_run``. Full detached software orchestration lives in
- ``tools/replay_review_compact.py``.
- """
- package_dir = package_dir.expanduser().resolve(strict=True)
- extract_root = extract_root.expanduser().resolve(strict=False)
- if extract_root.exists():
- raise PackagingError(f"replay extract root already exists: {extract_root}")
- index_path = package_dir / "HANDOFF-INDEX.json"
- sums_path = package_dir / "SHA256SUMS.txt"
- exclusions_path = package_dir / "EXCLUSIONS.txt"
- if not index_path.is_file() or not sums_path.is_file():
- raise PackagingError("package directory is missing HANDOFF-INDEX.json or SHA256SUMS.txt")
- index = json.loads(index_path.read_text(encoding="utf-8"))
- extract_root.mkdir(parents=True, exist_ok=False)
- zip_extract_root = extract_root / "from-zip"
- tar_extract_root = extract_root / "from-tar-zst"
- zip_extract_root.mkdir(parents=True, exist_ok=True)
- verified_volumes: list[dict[str, object]] = []
- verified_sidecars: list[dict[str, object]] = []
- tar_zst_name: str | None = None
- for line in sums_path.read_text(encoding="ascii").splitlines():
- line = line.strip()
- if not line or line.startswith("#"):
- continue
- digest, _, name = line.partition(" ")
- if not digest or not name:
- raise PackagingError(f"invalid SHA256SUMS line: {line}")
- member_path = package_dir / name
- actual = handoff.sha256_file(member_path)
- if actual != digest:
- raise PackagingError(f"SHA256SUMS mismatch for {name}")
- lower = name.casefold()
- if lower.endswith(".zip"):
- with zipfile.ZipFile(member_path, "r", allowZip64=True) as archive:
- archive.extractall(zip_extract_root)
- verified_volumes.append({"file": name, "sha256": actual})
- elif lower.endswith(".tar.zst"):
- tar_zst_name = name
- tar_extract_root.mkdir(parents=True, exist_ok=True)
- completed = subprocess.run(
- ["tar", "--zstd", "-xf", str(member_path), "-C", str(tar_extract_root)],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- )
- if completed.returncode != 0:
- raise PackagingError(
- f"unable to extract tar.zst during replay: {name}: "
- f"{completed.stderr.decode('utf-8', errors='replace').strip()}"
- )
- verified_sidecars.append({"file": name, "sha256": actual, "kind": "tar_zst"})
- else:
- verified_sidecars.append({"file": name, "sha256": actual, "kind": "sidecar"})
- checked_files = 0
- for item in index.get("files", []):
- relative = str(item["path"])
- target = zip_extract_root / "CPLD" / Path(*relative.split("/"))
- if not target.is_file():
- raise PackagingError(f"replay missing extracted file: {relative}")
- digest = handoff.sha256_file(target)
- if digest != item["sha256"] or target.stat().st_size != int(item["size"]):
- raise PackagingError(f"replay hash mismatch for {relative}")
- if tar_zst_name is not None:
- # tar.zst is created from ZIP extract roots, so the same CPLD tree must round-trip.
- tar_target = tar_extract_root / "CPLD" / Path(*relative.split("/"))
- if not tar_target.is_file():
- raise PackagingError(f"tar.zst replay missing extracted file: {relative}")
- if handoff.sha256_file(tar_target) != digest:
- raise PackagingError(f"tar.zst replay hash mismatch for {relative}")
- checked_files += 1
- for record in index.get("content_dedup", []):
- physical = zip_extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
- if not physical.is_file():
- raise PackagingError(f"replay missing dedup physical file: {record['physical_path']}")
- for alias in record.get("logical_paths", []):
- alias_path = zip_extract_root / "CPLD" / Path(*str(alias).split("/"))
- if alias_path.exists():
- raise PackagingError(f"replay found duplicated physical alias path: {alias}")
- cpld_root = zip_extract_root / "CPLD"
- return {
- "status": "pass",
- "mode": "package_replay",
- "package_dir": str(package_dir),
- "extract_root": str(extract_root),
- "cpld_root": str(cpld_root) if cpld_root.is_dir() else None,
- "volumes": verified_volumes,
- "sidecars": verified_sidecars,
- "exclusions_present": exclusions_path.is_file(),
- "tar_zst": tar_zst_name,
- "checked_files": checked_files,
- "content_dedup_groups": len(index.get("content_dedup", [])),
- "derived_evidence_count": len(index.get("derived_evidence", [])),
- # Four-state skeleton (content only; software lane filled by replay_review_compact).
- "package_content_replay": "pass",
- "detached_software_replay": "not_run",
- "reference_regeneration_replay": "not_packaged_by_policy",
- "hardware_validation": "not_run",
- }
- def _audit_one_item(item: PackageItem) -> dict[str, object]:
- if item.scan_archive:
- file_inventory = handoff.stream_candidate(item.candidate)
- else:
- file_inventory = handoff.hash_candidate(item.candidate)
- return {
- **file_inventory,
- "archive_path": f"CPLD/{item.candidate.relative}",
- "category": item.category,
- "source_id": item.source_id,
- "original_path": item.original_path,
- }
- def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
- sorted_items = sorted(items, key=_item_sort_key)
- collision_paths: dict[str, str] = {}
- for item in sorted_items:
- key = handoff.windows_collision_key(item.candidate.relative)
- previous = collision_paths.get(key)
- if previous is not None:
- raise PackagingError(
- f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
- )
- collision_paths[key] = item.candidate.relative
- max_workers = os.cpu_count() or 1
- with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
- return list(executor.map(_audit_one_item, sorted_items))
- def _write_unscanned_candidate(
- archive: zipfile.ZipFile,
- item: PackageItem,
- ) -> dict[str, object]:
- candidate = item.candidate
- digest = hashlib.sha256()
- total = 0
- secret_tail = b""
- entry_name = f"CPLD/{candidate.relative}"
- try:
- with archive.open(handoff.zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
- with handoff.open_candidate(candidate) as source:
- for chunk in iter(lambda: source.read(1024 * 1024), b""):
- secret_tail = handoff.scan_secret_markers(
- chunk,
- secret_tail,
- candidate.relative,
- )
- target.write(chunk)
- digest.update(chunk)
- total += len(chunk)
- except OSError as exc:
- raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
- if total != candidate.size:
- raise PackagingError(f"source size changed during packaging: {candidate.relative}")
- return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
- def _write_package_item(
- archive: zipfile.ZipFile,
- item: PackageItem,
- ) -> dict[str, object]:
- if item.scan_archive:
- return handoff.write_candidate(archive, item.candidate)
- return _write_unscanned_candidate(archive, item)
- def _stage_package_item(
- staging_root: Path,
- item: PackageItem,
- staging_name: str,
- ) -> dict[str, object]:
- target = staging_root / "CPLD" / staging_name
- target.parent.mkdir(parents=True, exist_ok=True)
- if item.scan_archive:
- try:
- with target.open("wb") as destination:
- return handoff.stream_candidate(item.candidate, target=destination)
- except OSError as exc:
- raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
- digest = hashlib.sha256()
- total = 0
- secret_tail = b""
- try:
- with handoff.open_candidate(item.candidate) as source, target.open("wb") as destination:
- for chunk in iter(lambda: source.read(1024 * 1024), b""):
- secret_tail = handoff.scan_secret_markers(
- chunk,
- secret_tail,
- item.candidate.relative,
- )
- destination.write(chunk)
- digest.update(chunk)
- total += len(chunk)
- except OSError as exc:
- raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
- if total != item.candidate.size:
- raise PackagingError(f"source size changed during staging: {item.candidate.relative}")
- return {"path": item.candidate.relative, "size": total, "sha256": digest.hexdigest()}
- def _volume_manifest(
- *,
- run_id: str,
- package_name: str,
- number: int,
- count: int,
- items: list[PackageItem],
- inventory_by_path: dict[str, dict[str, object]],
- ) -> dict[str, object]:
- categories = sorted({item.category for item in items})
- entries = [inventory_by_path[item.candidate.relative] for item in items]
- return {
- "schema": "cpld-agent-analysis-volume-v1",
- "run_id": run_id,
- "package_name": package_name,
- "volume_number": number,
- "volume_count": count,
- "categories": categories,
- "file_count": len(entries),
- "uncompressed_bytes": sum(int(entry["size"]) for entry in entries),
- "files": entries,
- }
- def _write_volume(
- path: Path,
- *,
- run_id: str,
- package_name: str,
- number: int,
- count: int,
- items: list[PackageItem],
- inventory_by_path: dict[str, dict[str, object]],
- ) -> dict[str, object]:
- manifest = _volume_manifest(
- run_id=run_id,
- package_name=package_name,
- number=number,
- count=count,
- items=items,
- inventory_by_path=inventory_by_path,
- )
- manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
- manifest_payload = handoff.json_bytes(manifest)
- written_inventory: list[dict[str, object]] = []
- try:
- with zipfile.ZipFile(
- path,
- "w",
- compression=zipfile.ZIP_DEFLATED,
- compresslevel=9,
- allowZip64=True,
- ) as archive:
- for item in sorted(items, key=_item_sort_key):
- expected = inventory_by_path[item.candidate.relative]
- if item.scan_archive:
- actual = handoff.write_candidate(archive, item.candidate)
- else:
- actual = _write_unscanned_candidate(archive, item)
- if (
- actual["size"] != expected["size"]
- or actual["sha256"] != expected["sha256"]
- ):
- raise PackagingError(
- f"source changed while writing ZIP: {item.candidate.relative}"
- )
- written_inventory.append(actual)
- with archive.open(
- handoff.zip_info(manifest_name), "w", force_zip64=True
- ) as target:
- target.write(manifest_payload)
- except (OSError, zipfile.BadZipFile) as exc:
- raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
- expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
- expected_names.add(manifest_name)
- handoff.verify_archive(
- path,
- expected_names=expected_names,
- inventory=written_inventory,
- expected_payloads={manifest_name: manifest_payload},
- )
- return {
- "file": path.name,
- "volume_number": number,
- "volume_count": count,
- "categories": manifest["categories"],
- "file_count": len(items),
- "uncompressed_bytes": manifest["uncompressed_bytes"],
- "compressed_bytes": path.stat().st_size,
- "sha256": handoff.sha256_file(path),
- }
- def _estimated_item_bytes(item: PackageItem) -> int:
- return item.candidate.size + 512 + (len(item.candidate.relative.encode("utf-8")) * 2)
- def _partition_items(
- items: tuple[PackageItem, ...],
- *,
- target_zip_bytes: int,
- ) -> list[list[PackageItem]]:
- base_overhead = min(64_000, max(1_024, target_zip_bytes // 20))
- groups: list[list[PackageItem]] = []
- current: list[PackageItem] = []
- current_category: str | None = None
- estimated_bytes = base_overhead
- for item in sorted(items, key=_item_sort_key):
- item_estimate = _estimated_item_bytes(item)
- if current and (
- item.category != current_category
- or estimated_bytes + item_estimate > target_zip_bytes
- ):
- groups.append(current)
- current = []
- estimated_bytes = base_overhead
- if not current:
- current_category = item.category
- current.append(item)
- estimated_bytes += item_estimate
- if current:
- groups.append(current)
- return groups
- def _split_oversized_groups(
- staging: Path,
- *,
- run_id: str,
- package_name: str,
- groups: list[list[PackageItem]],
- inventory_by_path: dict[str, dict[str, object]],
- target_zip_bytes: int,
- max_zip_bytes: int,
- ) -> list[list[PackageItem]]:
- pending = list(groups)
- accepted: list[list[PackageItem]] = []
- probe_number = 0
- while pending:
- group = pending.pop(0)
- probe_number += 1
- probe = staging / f".volume-probe-{probe_number:04d}.zip"
- try:
- _write_volume(
- probe,
- run_id=run_id,
- package_name=package_name,
- number=1,
- count=1,
- items=group,
- inventory_by_path=inventory_by_path,
- )
- size = probe.stat().st_size
- finally:
- probe.unlink(missing_ok=True)
- if size < max_zip_bytes and (size <= target_zip_bytes or len(group) == 1):
- accepted.append(group)
- continue
- if len(group) == 1:
- raise PackagingError(
- f"single analysis file requires chunking before ZIP creation: {group[0].candidate.relative}"
- )
- middle = len(group) // 2
- pending[0:0] = [group[:middle], group[middle:]]
- return accepted
- def _prepare_large_file_chunks(
- staging: Path,
- *,
- run_id: str,
- package_name: str,
- items: tuple[PackageItem, ...],
- inventory_by_path: dict[str, dict[str, object]],
- target_zip_bytes: int,
- max_zip_bytes: int,
- ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], Path | None]:
- packaged_items: list[PackageItem] = []
- large_files: list[dict[str, object]] = []
- chunk_root: Path | None = None
- probe_number = 0
- chunk_payload_bytes = max(1, (target_zip_bytes * 3) // 4)
- for item in sorted(items, key=_item_sort_key):
- must_probe = _estimated_item_bytes(item) > target_zip_bytes
- if must_probe:
- probe_number += 1
- probe = staging / f".large-file-probe-{probe_number:04d}.zip"
- try:
- _write_volume(
- probe,
- run_id=run_id,
- package_name=package_name,
- number=1,
- count=1,
- items=[item],
- inventory_by_path=inventory_by_path,
- )
- probe_size = probe.stat().st_size
- finally:
- probe.unlink(missing_ok=True)
- if probe_size <= target_zip_bytes and probe_size < max_zip_bytes:
- packaged_items.append(item)
- continue
- else:
- packaged_items.append(item)
- continue
- if chunk_root is None:
- chunk_root = staging / ".large-file-chunks"
- chunk_root.mkdir()
- original = inventory_by_path[item.candidate.relative]
- file_id = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
- file_chunk_root = chunk_root / file_id
- file_chunk_root.mkdir()
- file_name = Path(item.candidate.relative).name
- chunks: list[dict[str, object]] = []
- original_digest = hashlib.sha256()
- original_bytes = 0
- secret_tail = b""
- with handoff.open_candidate(item.candidate) as source:
- number = 0
- while True:
- payload = source.read(chunk_payload_bytes)
- if not payload:
- break
- number += 1
- secret_tail = handoff.scan_secret_markers(
- payload,
- secret_tail,
- item.candidate.relative,
- )
- original_digest.update(payload)
- original_bytes += len(payload)
- chunk_name = f"{file_name}.part{number:04d}"
- chunk_path = file_chunk_root / chunk_name
- with chunk_path.open("xb") as handle:
- handle.write(payload)
- chunk_relative = f"HANDOFF-LARGE-FILES/{file_id}/{chunk_name}"
- chunk_item = make_package_item(
- chunk_path,
- relative=chunk_relative,
- category=item.category,
- source_id=item.source_id,
- scan_archive=False,
- )
- packaged_items.append(chunk_item)
- chunks.append(
- {
- "number": number,
- "path": chunk_relative,
- "archive_path": f"CPLD/{chunk_relative}",
- "size": len(payload),
- "sha256": hashlib.sha256(payload).hexdigest(),
- }
- )
- if original_bytes != original["size"] or original_digest.hexdigest() != original["sha256"]:
- raise PackagingError(f"source changed while splitting large file: {item.candidate.relative}")
- if len(chunks) < 2:
- raise PackagingError(f"large file split did not produce multiple chunks: {item.candidate.relative}")
- large_files.append(
- {
- "path": item.candidate.relative,
- "category": item.category,
- "source_id": item.source_id,
- "original_path": item.original_path,
- "size": original["size"],
- "sha256": original["sha256"],
- "chunks": chunks,
- }
- )
- return tuple(packaged_items), large_files, chunk_root
- def _assert_items_unchanged(
- items: tuple[PackageItem, ...],
- inventory_by_path: dict[str, dict[str, object]],
- ) -> None:
- for item in items:
- current = handoff.hash_candidate(item.candidate)
- expected = inventory_by_path[item.candidate.relative]
- if current["size"] != expected["size"] or current["sha256"] != expected["sha256"]:
- raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
- def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: str = "full") -> None:
- for snapshot in collection.source_snapshots:
- # Prefer the profile captured at collection time so review-compact
- # snapshots are not re-scanned under the create_analysis_package default.
- check_profile = snapshot.profile or profile
- current = _source_snapshot(
- snapshot.root,
- source_id=snapshot.source_id,
- extra_exclusions=snapshot.extra_exclusions,
- profile=check_profile,
- )
- if (
- current.candidates != snapshot.candidates
- or current.excluded != snapshot.excluded
- ):
- raise PackagingError("source tree changed during analysis packaging: retry from a stable workspace snapshot")
- def _start_here_text(package_name: str, volume_count: int, *, profile: str = "full") -> str:
- base = (
- f"# {package_name} 分析交付包\n\n"
- f"本目录包含 {volume_count} 个互相独立的普通 ZIP,以及可选的 `.tar.zst` 同源归档。"
- "请先核对 `SHA256SUMS.txt`,再把所有 ZIP 解压到同一个目录;"
- "也可用 `tar --zstd -xf <package>.tar.zst` 还原。\n\n"
- "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256,"
- "`EXCLUSIONS.txt` 列出排除路径与规则,"
- "以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
- "不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
- )
- if handoff.uses_unified_layout(profile):
- return base + (
- "本包为统一布局:`source/` + `evidence/` + `meta/`。\n"
- "`PACKAGE-PURPOSE.txt` 说明上传意图;`size-budget.json` 列出 ≥256KiB 或 >1% 体积的成员。\n"
- "默认 **不含** 完整 Git bundle;`meta/git/` 提供 commit/status/log-20/tree/逐文件 SHA-256 "
- "与 TD source-closure 绑定钩子。\n"
- "成员计数:`member_count.indexed_files` 对应 ZIP 内业务文件;"
- "`self_reference_control_files` 是包目录控制文件(亦列入 SHA256SUMS),"
- "不要把控制文件与 ZIP payload 成员重复加总。\n"
- )
- return base + (
- "完整 full 包必须包含 `git-history/*.bundle`,以便在干净提取后用 commit-to-commit "
- "恢复 source closure 比对。\n"
- )
- def build_member_count_semantics(
- *,
- indexed_files: int,
- zip_file_entries: int,
- control_files: tuple[str, ...] = SELF_REFERENCE_CONTROL_FILES,
- ) -> dict[str, object]:
- return {
- "indexed_files": indexed_files,
- "zip_file_entries": zip_file_entries,
- "self_reference_control_files": list(control_files),
- "note": (
- "indexed_files counts HANDOFF-INDEX files[] (ZIP payload business members). "
- "zip_file_entries counts non-directory ZIP entries including VOLUME-MANIFEST. "
- "self_reference_control_files live in the package directory and appear in "
- "SHA256SUMS; do not add them again to indexed_files."
- ),
- }
- def write_exclusions_text(excluded: list[dict[str, object]]) -> str:
- """Render a portable EXCLUSIONS.txt for the package sidecar layout."""
- lines = [
- "# path<TAB>rule",
- "# Inclusion-first package: only versioned recursive exclusions are listed.",
- ]
- for item in sorted(excluded, key=lambda row: handoff.windows_collision_key(str(row.get("path", "")))):
- path = str(item.get("path", ""))
- rule = str(item.get("rule", item.get("reason", "excluded")))
- lines.append(f"{path}\t{rule}")
- return "\n".join(lines) + "\n"
- def create_tar_zst_archive(source_dir: Path, archive_path: Path) -> str:
- """Create a deterministic-enough tar.zst of source_dir contents; return SHA-256."""
- source_dir = source_dir.resolve(strict=True)
- archive_path = archive_path.resolve(strict=False)
- if archive_path.exists():
- archive_path.unlink()
- zstd = shutil.which("zstd")
- if zstd is None:
- raise PackagingError("zstd is required to create .tar.zst package archives")
- # Prefer GNU tar --zstd when available; fall back to compress-program.
- command = [
- "tar",
- "--zstd",
- "-cf",
- str(archive_path),
- "--sort=name",
- "--mtime=UTC 1980-01-01",
- "--owner=0",
- "--group=0",
- "--numeric-owner",
- "-C",
- str(source_dir),
- ".",
- ]
- completed = subprocess.run(
- command,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- )
- if completed.returncode != 0:
- # Older tar without --zstd / --sort: use compress-program path.
- fallback = [
- "tar",
- "-cf",
- str(archive_path),
- "-I",
- zstd,
- "-C",
- str(source_dir),
- ".",
- ]
- completed = subprocess.run(
- fallback,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- check=False,
- )
- if completed.returncode != 0:
- detail = completed.stderr.decode("utf-8", errors="replace").strip()
- raise PackagingError(f"unable to create tar.zst archive: {detail or 'tar failed'}")
- return handoff.sha256_file(archive_path)
- def write_package_layout_sidecars(
- staging: Path,
- *,
- index: dict[str, object],
- excluded: list[dict[str, object]],
- package_name: str,
- include_tar_zst: bool = True,
- profile: str = "full",
- size_budget: dict[str, object] | None = None,
- ) -> list[dict[str, object]]:
- """Write index/checksums/exclusions and optional tar.zst; return checksum rows."""
- staging.mkdir(parents=True, exist_ok=True)
- (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
- (staging / "EXCLUSIONS.txt").write_text(
- write_exclusions_text(excluded),
- encoding="utf-8",
- newline="\n",
- )
- (staging / "PACKAGE-PURPOSE.txt").write_text(
- handoff.package_purpose_text(profile, package_name=package_name),
- encoding="utf-8",
- newline="\n",
- )
- (staging / "START-HERE.zh-CN.md").write_text(
- _start_here_text(package_name, len(index.get("volumes", [])), profile=profile),
- encoding="utf-8",
- newline="\n",
- )
- if size_budget is not None:
- (staging / "size-budget.json").write_bytes(handoff.json_bytes(size_budget))
- checksum_rows: list[dict[str, object]] = []
- for info in index.get("volumes", []):
- name = str(info["file"])
- checksum_rows.append({"file": name, "sha256": str(info["sha256"])})
- if include_tar_zst:
- # Stage CPLD tree from ZIP volumes into a temporary extract for tar.zst.
- extract_root = staging / ".tar-zst-staging"
- if extract_root.exists():
- shutil.rmtree(extract_root)
- extract_root.mkdir(parents=True, exist_ok=True)
- for info in index.get("volumes", []):
- volume_path = staging / str(info["file"])
- with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
- archive.extractall(extract_root)
- tar_name = f"{package_name}.tar.zst"
- tar_path = staging / tar_name
- tar_sha = create_tar_zst_archive(extract_root, tar_path)
- shutil.rmtree(extract_root)
- checksum_rows.append({"file": tar_name, "sha256": tar_sha})
- index["formats"] = {
- "zip_volumes": [str(info["file"]) for info in index.get("volumes", [])],
- "tar_zst": tar_name,
- "tar_zst_sha256": tar_sha,
- }
- (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
- sidecar_names = [
- "HANDOFF-INDEX.json",
- "EXCLUSIONS.txt",
- "PACKAGE-PURPOSE.txt",
- "START-HERE.zh-CN.md",
- ]
- if size_budget is not None:
- sidecar_names.append("size-budget.json")
- for sidecar in sidecar_names:
- checksum_rows.append(
- {"file": sidecar, "sha256": handoff.sha256_file(staging / sidecar)}
- )
- checksum_lines = [f"{row['sha256']} {row['file']}" for row in checksum_rows]
- (staging / "SHA256SUMS.txt").write_text(
- "\n".join(checksum_lines) + "\n",
- encoding="ascii",
- newline="\n",
- )
- return checksum_rows
- def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
- backup: Path | None = None
- backup_created = False
- new_directory_published = False
- if os.path.lexists(final):
- if not force:
- raise PackagingError(f"package output already exists: {final}")
- file_stat = os.lstat(final)
- if not stat.S_ISDIR(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
- raise PackagingError(f"existing package output is not a regular directory: {final}")
- backup = final.with_name(f".{final.name}.{uuid.uuid4().hex}.backup")
- try:
- if backup is not None:
- os.replace(final, backup)
- backup_created = True
- os.replace(staging, final)
- new_directory_published = True
- except BaseException as exc:
- if new_directory_published and os.path.lexists(final):
- try:
- shutil.rmtree(final)
- except OSError:
- pass
- if backup_created and backup is not None and os.path.lexists(backup):
- try:
- os.replace(backup, final)
- except OSError as rollback_exc:
- raise PackagingError(
- f"package publication failed and rollback was incomplete: {rollback_exc}"
- ) from exc
- if isinstance(exc, PackagingError):
- raise
- raise PackagingError(f"unable to publish package directory atomically: {exc}") from exc
- if backup is not None:
- shutil.rmtree(backup)
- def create_analysis_package(
- *,
- collection: AnalysisCollection,
- output_root: Path,
- package_name: str,
- max_zip_bytes: int,
- target_zip_bytes: int,
- force: bool,
- profile: str = "full",
- ) -> dict[str, object]:
- _validate_package_name(package_name)
- if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
- raise PackagingError("ZIP size limits are invalid")
- if not collection.items:
- raise PackagingError("analysis package has no included files")
- output_root = output_root.expanduser().resolve(strict=False)
- output_root.mkdir(parents=True, exist_ok=True)
- final_dir = output_root / package_name
- if os.path.lexists(final_dir) and not force:
- raise PackagingError(f"package output already exists: {final_dir}")
- run_id = uuid.uuid4().hex
- staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
- try:
- full_inventory = _audit_package_items(collection.items)
- physical_items, content_dedup, dedup_excluded = apply_content_dedup(
- collection.items,
- full_inventory,
- )
- inventory = [
- row
- for row in full_inventory
- if str(row["path"]) in {item.candidate.relative for item in physical_items}
- ]
- inventory_by_path = {str(item["path"]): item for item in inventory}
- package_excluded = list(collection.excluded) + dedup_excluded
- package_excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
- derived_evidence = classify_derived_evidence(physical_items)
- evidence_canon_fields = dict(collection.evidence_canon or {})
- # Merge content_dedup logical aliases into evidence_canon.aliases for HANDOFF-INDEX.
- evidence_aliases = list(evidence_canon_fields.get("aliases", [])) # type: ignore[arg-type]
- for record in content_dedup:
- evidence_aliases.append(
- {
- "key": None,
- "sha256": record["sha256"],
- "size": record["size"],
- "physical_path": record["physical_path"],
- "logical_paths": record["logical_paths"],
- "reason": record["reason"],
- }
- )
- if evidence_canon_fields:
- evidence_canon_fields["aliases"] = evidence_aliases
- package_items = physical_items
- package_inventory = inventory
- package_inventory_by_path = inventory_by_path
- large_files: list[dict[str, object]] = []
- chunk_root: Path | None = None
- single_path = staging / f"{package_name}.zip"
- single_info = _write_volume(
- single_path,
- run_id=run_id,
- package_name=package_name,
- number=1,
- count=1,
- items=list(sorted(physical_items, key=_item_sort_key)),
- inventory_by_path=inventory_by_path,
- )
- if single_path.stat().st_size < max_zip_bytes:
- volume_infos = [single_info]
- groups = [list(sorted(physical_items, key=_item_sort_key))]
- else:
- single_path.unlink()
- package_items, large_files, chunk_root = _prepare_large_file_chunks(
- staging,
- run_id=run_id,
- package_name=package_name,
- items=physical_items,
- inventory_by_path=inventory_by_path,
- target_zip_bytes=target_zip_bytes,
- max_zip_bytes=max_zip_bytes,
- )
- package_inventory = _audit_package_items(package_items)
- package_inventory_by_path = {
- str(item["path"]): item for item in package_inventory
- }
- initial_groups = _partition_items(
- package_items,
- target_zip_bytes=target_zip_bytes,
- )
- groups = _split_oversized_groups(
- staging,
- run_id=run_id,
- package_name=package_name,
- groups=initial_groups,
- inventory_by_path=package_inventory_by_path,
- target_zip_bytes=target_zip_bytes,
- max_zip_bytes=max_zip_bytes,
- )
- volume_infos = []
- count = len(groups)
- for number, group in enumerate(groups, start=1):
- category = group[0].category if len({item.category for item in group}) == 1 else "mixed"
- safe_category = re.sub(r"[^a-z0-9]+", "-", category.casefold()).strip("-") or "data"
- volume_path = staging / f"{package_name}.part{number:03d}-{safe_category}.zip"
- volume_info = _write_volume(
- volume_path,
- run_id=run_id,
- package_name=package_name,
- number=number,
- count=count,
- items=group,
- inventory_by_path=package_inventory_by_path,
- )
- if volume_path.stat().st_size >= max_zip_bytes:
- raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
- volume_infos.append(volume_info)
- volume_by_path: dict[str, str] = {}
- for volume_info, group in zip(volume_infos, groups, strict=True):
- for item in group:
- volume_by_path[item.candidate.relative] = str(volume_info["file"])
- large_paths = {str(item["path"]) for item in large_files}
- indexed_files = [
- {**item, "volume": volume_by_path[str(item["path"])]}
- for item in inventory
- if str(item["path"]) not in large_paths
- ]
- for large_file in large_files:
- for chunk in large_file["chunks"]:
- chunk["volume"] = volume_by_path[str(chunk["path"])]
- zip_entry_count = 0
- for info in volume_infos:
- volume_path = staging / str(info["file"])
- with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
- zip_entry_count += sum(1 for name in archive.namelist() if not name.endswith("/"))
- size_budget = handoff.build_size_budget(
- inventory,
- zip_total_bytes=sum(int(info["compressed_bytes"]) for info in volume_infos),
- )
- member_count = build_member_count_semantics(
- indexed_files=len(indexed_files),
- zip_file_entries=zip_entry_count,
- )
- index = {
- "schema": "cpld-agent-analysis-index-v1",
- "run_id": run_id,
- "created_at_utc": _utc_now(),
- "package_name": package_name,
- "status": collection.status,
- "profile": profile,
- "delivery_policy": handoff.delivery_policy_for_profile(profile),
- "max_zip_bytes": max_zip_bytes,
- "target_zip_bytes": target_zip_bytes,
- "sources": list(collection.sources),
- "git": list(collection.git),
- "warnings": list(collection.warnings),
- "excluded": package_excluded,
- "content_dedup": content_dedup,
- "derived_evidence": derived_evidence,
- "evidence_canon": evidence_canon_fields if evidence_canon_fields else None,
- "evidence_aliases": evidence_aliases,
- "member_count": member_count,
- "size_budget": size_budget,
- "volumes": volume_infos,
- "files": indexed_files,
- "large_files": large_files,
- }
- if large_files:
- (staging / "reassemble_large_files.py").write_text(
- REASSEMBLER_SCRIPT,
- encoding="utf-8",
- newline="\n",
- )
- for info in volume_infos:
- volume_path = staging / str(info["file"])
- if volume_path.stat().st_size >= max_zip_bytes:
- raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
- if handoff.sha256_file(volume_path) != info["sha256"]:
- raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
- checksum_rows = write_package_layout_sidecars(
- staging,
- index=index,
- excluded=package_excluded,
- package_name=package_name,
- include_tar_zst=True,
- profile=profile,
- size_budget=size_budget if handoff.uses_unified_layout(profile) else None,
- )
- full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
- _assert_items_unchanged(collection.items, full_inventory_by_path)
- _assert_source_trees_unchanged(collection, profile=profile)
- # Fail-closed for final-review: stage-aware ZIP selftest must pass in
- # staging before any final-looking artifact is published atomically.
- # Intermediate-review keeps structure checks but is not a final gate.
- if profile == "review-compact":
- from compact_package_selftest import ( # noqa: WPS433
- PACKAGE_STAGE_FINAL,
- run_compact_package_selftest,
- )
- staged_report = run_compact_package_selftest(
- staging,
- skip_software=True,
- write_evidence=False,
- package_stage=None,
- )
- if (
- staged_report.get("package_stage") == PACKAGE_STAGE_FINAL
- and staged_report.get("status") != "pass"
- ):
- raise PackagingError(
- "review-compact final-review staging selftest failed before publish: "
- + ", ".join(staged_report.get("failures") or ["unknown"])
- )
- if chunk_root is not None:
- shutil.rmtree(chunk_root)
- _publish_directory_atomically(staging, final_dir, force=force)
- except BaseException:
- if os.path.lexists(staging):
- shutil.rmtree(staging, ignore_errors=True)
- raise
- formats = {}
- index_path = final_dir / "HANDOFF-INDEX.json"
- if index_path.is_file():
- formats = json.loads(index_path.read_text(encoding="utf-8")).get("formats", {})
- return {
- "status": collection.status,
- "mode": "package",
- "profile": profile,
- "delivery_policy": handoff.delivery_policy_for_profile(profile),
- "run_id": run_id,
- "output_dir": str(final_dir),
- "volumes": volume_infos,
- "formats": formats,
- "checksum_entries": len(checksum_rows),
- "included_file_count": len(inventory),
- "included_bytes": sum(int(item["size"]) for item in inventory),
- "excluded_entry_count": len(package_excluded),
- "content_dedup_groups": len(content_dedup),
- "derived_evidence_count": len(derived_evidence),
- "member_count": member_count,
- "warning_count": len(collection.warnings),
- }
- def _reference_fingerprint(inventory: list[dict[str, object]]) -> str:
- digest = hashlib.sha256()
- for item in sorted(inventory, key=lambda row: str(row["path"])):
- path = str(item["path"])
- size = str(item["size"])
- sha = str(item["sha256"])
- digest.update(f"{path}|{size}|{sha}\n".encode("utf-8"))
- return digest.hexdigest()
- def _create_reference_package_with_cache(
- *,
- collection: AnalysisCollection,
- output_root: Path,
- package_name: str,
- max_zip_bytes: int,
- target_zip_bytes: int,
- force: bool,
- repo_root: Path | None = None,
- refresh_reference_inventory: bool = False,
- ) -> dict[str, object]:
- reference_package_name = f"{package_name}-reference"
- reference_dir = output_root / reference_package_name
- fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
- inventory_hook: dict[str, object] | None = None
- if refresh_reference_inventory and repo_root is not None:
- # Order: staging of reference sources is complete before this call; refresh
- # inventory now so the package includes a fresh REFERENCE-INVENTORY.
- inventory_hook = handoff.run_post_staging_reference_inventory_hook(
- repo_root,
- staging_complete=True,
- enabled=True,
- )
- if inventory_hook.get("status") not in {"pass", "skipped_disabled"}:
- raise PackagingError(
- "post-staging reference inventory refresh failed: "
- f"{inventory_hook.get('status')}"
- )
- inventory = _audit_package_items(collection.items)
- fingerprint = _reference_fingerprint(inventory)
- if not force and fingerprint_path.exists():
- previous = fingerprint_path.read_text(encoding="ascii").strip()
- if previous == fingerprint:
- index_path = reference_dir / "HANDOFF-INDEX.json"
- if index_path.exists():
- index = json.loads(index_path.read_text(encoding="utf-8"))
- return {
- "status": collection.status,
- "mode": "reference_cached",
- "package_name": reference_package_name,
- "output_dir": str(reference_dir),
- "volumes": index.get("volumes", []),
- "included_file_count": len(inventory),
- "included_bytes": sum(int(item["size"]) for item in inventory),
- "fingerprint": fingerprint,
- "skipped": True,
- "reference_inventory_hook": inventory_hook,
- }
- payload = create_analysis_package(
- collection=collection,
- output_root=output_root,
- package_name=reference_package_name,
- max_zip_bytes=max_zip_bytes,
- target_zip_bytes=target_zip_bytes,
- force=force,
- )
- reference_dir = Path(payload["output_dir"])
- fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
- fingerprint_path.write_text(fingerprint + "\n", encoding="ascii")
- payload["fingerprint"] = fingerprint
- payload["skipped"] = False
- payload["reference_inventory_hook"] = inventory_hook
- return payload
- def merge_archive_preparation(
- collection: AnalysisCollection,
- preparation: ArchivePreparation,
- ) -> AnalysisCollection:
- warnings = (*collection.warnings, *preparation.warnings)
- excluded = sorted(
- (*collection.excluded, *preparation.excluded),
- key=lambda item: handoff.windows_collision_key(item["path"]),
- )
- return AnalysisCollection(
- status="pass_with_warnings" if warnings else "pass",
- items=preparation.items,
- excluded=tuple(excluded),
- warnings=tuple(warnings),
- sources=collection.sources,
- git=collection.git,
- source_snapshots=collection.source_snapshots,
- )
- def explain_analysis_path(
- path: Path,
- *,
- repo_root: Path,
- config: HandoffConfig,
- profile: str = "full",
- ) -> dict[str, object]:
- root = repo_root.resolve(strict=True)
- requested = path if path.is_absolute() else root / path
- target = requested.expanduser().resolve(strict=False)
- resolved_sources, warnings = resolve_external_sources(config.external_sources)
- source_roots: list[tuple[str, str, Path, Path | None]] = [
- ("workspace-current", "core", root, None)
- ]
- for source in resolved_sources:
- if source.kind == "file":
- source_roots.append((source.id, source.category, source.path.parent, source.path))
- else:
- source_roots.append((source.id, source.category, source.path, None))
- matches: list[tuple[int, str, str, Path, Path | None]] = []
- for source_id, category, source_root, exact_file in source_roots:
- if exact_file is not None and target != exact_file:
- continue
- try:
- target.relative_to(source_root)
- except ValueError:
- continue
- matches.append((len(source_root.parts), source_id, category, source_root, exact_file))
- if not matches:
- raise PackagingError("path is outside the current repository and configured external sources")
- _, source_id, category, source_root, exact_file = max(matches, key=lambda item: item[0])
- relative = exact_file.name if exact_file is not None else target.relative_to(source_root).as_posix()
- if not relative:
- relative = "."
- is_dir = target.is_dir()
- context = handoff.load_scan_context(source_root)
- reason = analysis_exclusion_reason(
- relative,
- is_dir=is_dir,
- context=context,
- extra_exclusions=config.extra_exclusions,
- profile=profile,
- )
- archive_relative = (
- f"workspace-current/{relative}"
- if source_id == "workspace-current"
- else f"external/{source_id}/{relative}"
- )
- return {
- "status": "pass_with_warnings" if warnings else "pass",
- "mode": "explain",
- "path": str(target),
- "exists": target.exists(),
- "source_id": source_id,
- "category": category,
- "source_relative_path": relative,
- "archive_path": f"CPLD/{archive_relative}",
- "decision": "exclude" if reason else "include",
- "reason": reason,
- "content_scan": "not_run",
- "warnings": warnings,
- }
- def audit_analysis_collection(collection: AnalysisCollection) -> dict[str, object]:
- inventory = _audit_package_items(collection.items)
- inventory_by_path = {str(item["path"]): item for item in inventory}
- _assert_items_unchanged(collection.items, inventory_by_path)
- return {
- "status": collection.status,
- "mode": "audit_only",
- "included_file_count": len(inventory),
- "included_bytes": sum(int(item["size"]) for item in inventory),
- "excluded_entry_count": len(collection.excluded),
- "warning_count": len(collection.warnings),
- "warnings": list(collection.warnings),
- "sources": list(collection.sources),
- "git": list(collection.git),
- }
- def _validate_output_root(
- output_root: Path,
- *,
- repo_root: Path,
- config: HandoffConfig,
- ) -> Path:
- output = output_root.expanduser().resolve(strict=False)
- source_paths = [repo_root.resolve(strict=True)]
- resolved_sources, _ = resolve_external_sources(config.external_sources)
- source_paths.extend(source.path if source.kind != "file" else source.path.parent for source in resolved_sources)
- for source_path in source_paths:
- try:
- output.relative_to(source_path)
- except ValueError:
- continue
- raise PackagingError(f"output directory must be outside every packaged source root: {source_path}")
- return output
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--audit-only", action="store_true", help="scan and verify inputs without creating ZIP files")
- parser.add_argument("--explain", type=Path, metavar="PATH", help="explain whether one path is included or excluded")
- parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="source and exclusion configuration JSON")
- parser.add_argument("--source-root", type=Path, default=ROOT, help="root directory to package as the primary source")
- parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help="parent directory for the package directory")
- parser.add_argument("--package-name", help="portable package directory and ZIP base name")
- parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
- parser.add_argument("--no-git-bundle", action="store_true", help="omit the git history bundle from the package")
- parser.add_argument(
- "--include-full-history",
- action="store_true",
- help="include a full git bundle (archive-local / explicit override; ignored as default for review-compact)",
- )
- parser.add_argument(
- "--include-sanitized-git-snapshot",
- action="store_true",
- help=(
- "include sanitized synthetic single-commit git snapshot under meta/git "
- "(records synthetic→original mapping; does not impersonate the original tip)"
- ),
- )
- parser.add_argument(
- "--evidence-root",
- type=Path,
- help=(
- "optional delivery/run evidence tree to stage into canonical evidence/ paths "
- "(final matrix, Formal/TD receipts, bitstream, selftests, deep-review summary, IO/hardware notes)"
- ),
- )
- parser.add_argument(
- "--include-process-evidence",
- action="store_true",
- help=(
- "include lane receipts, matrix reruns, and other process evidence "
- "(implied by review-debug; off by default for review-compact)"
- ),
- )
- parser.add_argument(
- "--profile",
- choices=sorted(handoff.HANDOFF_PROFILES),
- default=handoff.DEFAULT_HANDOFF_PROFILE,
- help=(
- "review-compact (default upload: unified source/evidence/meta, no full git bundle); "
- "review-debug; archive-local; legacy full (core/reference split) / code-only"
- ),
- )
- parser.add_argument(
- "--replay-package",
- type=Path,
- metavar="DIR",
- help="verify SHA256SUMS and replay-extract an existing package directory (selftest)",
- )
- parser.add_argument(
- "--replay-extract-dir",
- type=Path,
- help="extract target for --replay-package (must not already exist)",
- )
- parser.add_argument(
- "--bitstream",
- type=Path,
- help=(
- "optional real bitstream to bind into meta/td-source-closure-binding.json "
- "(full SHA-256; integrator supplies tip bit later)"
- ),
- )
- parser.add_argument(
- "--td-report",
- type=Path,
- action="append",
- default=[],
- dest="td_reports",
- help="optional TD report/receipt to bind (repeatable)",
- )
- parser.add_argument(
- "--binding-commit",
- help="optional full 40-char commit override for TD source-closure binding",
- )
- parser.add_argument(
- "--require-bitstream-binding",
- action="store_true",
- help="fail binding (status=bind_failed) when no bitstream is available",
- )
- parser.add_argument(
- "--package-stage",
- choices=("intermediate-review", "final-review"),
- default="final-review",
- help=(
- "intermediate-review: non-final code review without fresh TD/bitstream; "
- "final-review: fail-closed on missing canonical TD/bitstream evidence"
- ),
- )
- parser.add_argument(
- "--refresh-reference-inventory-after-staging",
- action="store_true",
- help=(
- "for full-profile reference volume: refresh docs/REFERENCE-INVENTORY "
- "after staging completes (Lane D order hook; Lane E owns generator honesty)"
- ),
- )
- return parser
- def main(argv: list[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- package_name = args.package_name or datetime.now(timezone.utc).strftime(
- "cpld-agent-analysis-%Y%m%dT%H%M%SZ"
- )
- try:
- if args.replay_package is not None:
- extract_root = args.replay_extract_dir or Path(
- tempfile.mkdtemp(prefix="prod2u-package-replay-", dir=os.environ.get("TMPDIR", "/tmp"))
- )
- payload = replay_analysis_package(args.replay_package, extract_root=extract_root)
- print(json.dumps(payload, ensure_ascii=False, indent=2))
- return 0
- source_root = args.source_root.expanduser().resolve(strict=True)
- if args.profile not in handoff.HANDOFF_PROFILES:
- raise PackagingError(f"unsupported handoff profile: {args.profile}")
- config = load_config(args.config, repo_root=source_root)
- if args.explain is not None:
- payload = explain_analysis_path(
- args.explain,
- repo_root=source_root,
- config=config,
- profile=args.profile,
- )
- else:
- seven_zip = find_7z()
- _validate_package_name(package_name)
- output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
- if args.profile == "archive-local":
- include_git_bundle = not args.no_git_bundle or args.include_full_history
- if args.include_full_history:
- include_git_bundle = True
- elif args.profile in {"review-compact", "review-debug"}:
- include_git_bundle = False
- else:
- include_git_bundle = not args.no_git_bundle
- with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
- temp_root = Path(temporary)
- collection = collect_analysis_inputs(
- repo_root=source_root,
- config=config,
- temp_root=temp_root / "inputs",
- include_git_bundle=include_git_bundle,
- profile=args.profile,
- include_sanitized_git_snapshot=args.include_sanitized_git_snapshot,
- package_name=package_name,
- evidence_root=args.evidence_root.expanduser().resolve(strict=True)
- if args.evidence_root is not None
- else None,
- include_process_evidence=args.include_process_evidence,
- bitstream_path=args.bitstream.expanduser().resolve(strict=True)
- if args.bitstream is not None
- else None,
- td_report_paths=[
- path.expanduser().resolve(strict=True) for path in args.td_reports
- ],
- binding_commit=args.binding_commit,
- require_bitstream_binding=args.require_bitstream_binding,
- package_stage=args.package_stage,
- )
- preparation = prepare_unsupported_archives(
- collection.items,
- temp_root=temp_root / "archives",
- seven_zip=seven_zip,
- extra_exclusions=config.extra_exclusions,
- )
- prepared_collection = merge_archive_preparation(collection, preparation)
- if args.audit_only:
- payload = audit_analysis_collection(prepared_collection)
- payload["profile"] = args.profile
- payload["delivery_policy"] = handoff.delivery_policy_for_profile(args.profile)
- elif handoff.uses_unified_layout(args.profile) or args.profile == "code-only":
- if not prepared_collection.items:
- raise PackagingError("analysis package has no included files")
- payload = create_analysis_package(
- collection=prepared_collection,
- output_root=output_root,
- package_name=package_name,
- max_zip_bytes=config.max_zip_bytes,
- target_zip_bytes=config.target_zip_bytes,
- force=args.force_overwrite,
- profile=args.profile,
- )
- else:
- core_collection, reference_collection = _split_collection_by_reference(
- prepared_collection
- )
- if not core_collection.items and not reference_collection.items:
- raise PackagingError("analysis package has no included files")
- payload = {}
- if core_collection.items:
- payload["core"] = create_analysis_package(
- collection=core_collection,
- output_root=output_root,
- package_name=package_name,
- max_zip_bytes=config.max_zip_bytes,
- target_zip_bytes=config.target_zip_bytes,
- force=args.force_overwrite,
- profile=args.profile,
- )
- if reference_collection.items:
- payload["reference"] = _create_reference_package_with_cache(
- collection=reference_collection,
- output_root=output_root,
- package_name=package_name,
- max_zip_bytes=config.max_zip_bytes,
- target_zip_bytes=config.target_zip_bytes,
- force=args.force_overwrite,
- repo_root=source_root,
- refresh_reference_inventory=args.refresh_reference_inventory_after_staging,
- )
- except (PackagingError, OSError, ValueError) as exc:
- print(f"error: {exc}", file=sys.stderr)
- return 1
- print(json.dumps(payload, ensure_ascii=False, indent=2))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|