"""Record applied final-27 trace lessons and fresh evidence for the 28 handoff."""
from pathlib import Path
import json,csv,hashlib
R=Path(__file__).resolve().parents[1];A=R/'audit';D=R/'documents';read=lambda n:json.loads((A/n).read_text());sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
g=read('independent_geometry_review.json');n=read('native_preservation_review.json');st=read('Concept_28_R1_static_audit.json');rt=read('Concept_28_R1_retention_audit.json');mo=read('Concept_28_R1_switch_motion.json');cv=read('Concept_28_R1_cover_insertion.json');fa=read('Concept_28_R1_fastener_access.json');usb=read('Concept_28_R1_USB_insertion.json');lte=read('Concept_28_R1_LTE_service_path.json');attach=read('Concept_28_R1_attachment_graph.json')
assert not g['validity_failures'] and not g['new_detected_interferences'] and not g['changed_vs_hardware_interferences']
assert not st['unintended'] and all(x['blocked_within_1_2mm'] for x in rt) and len(rt)==60
assert all(x['cad_sweep_clear'] and x['actuator_contact_reached'] for x in mo) and len(mo)==4
assert all(not x['hits'] for x in cv['samples']) and all(not x['tool_hits']for x in fa)
assert all(not x['case_part_hits']for x in usb['samples'])
assert all(x['overlap_with_back_mm3']<1e-5 for path in lte.values() for x in path)
assert not n['unchanged_assembly_occurrences']['mismatches']
assert all(x['volume_mm3']<1e-6 for x in n['front_shell_below_z_minus_2_21_mm']['directional_differences'])
capture=read('Concept_28_R1_control_capture.json')
assert len(capture['checks'])==24 and all(x['stops'] for x in capture['checks'])
updates=[
 ['Source authority','Use the actual completed final R2 package, not an earlier checkpoint or prior PASS label.','Imported final R2 STEP into Fusion; source package SHA-256 recorded. Existing public 27 R2 and UC1 remain unchanged.'],
 ['PCB retention','Locate supports on bare FR4, and inspect the real primary substrate.','Paired pads/supports at (-27,-33.7), (-27,-4), (27,8), (27,17) mm; 6-direction primary-FR4 check passed.'],
 ['Battery and leads','Extend guides and provide a central service route without squeezing the pouch.','Final rails/liners and +/-17.2 mm central gate retained; two full-length 1.2 mm lead-route references retained. Nominal route is not a qualified harness.'],
 ['Speaker','Use the final split gasket stack and actual mounting datums.','38.0 mm-ID gasket stack, rated membrane and mounting bosses at X +/-9.1, Y 18/66 mm. New shell opening is 35.0 mm.'],
 ['LTE retention','Separate upper/lower frames across the no-stack divider and include soft edge stops.','Both service frames, four stops, dielectric seat and bond retained; both removal paths clear through 16 mm sampled lift.'],
 ['Rim retention','Provide hidden grip pads without bridging the service seam.','Four final front-shell-only grip pads retained; 0.15 mm installed / 0.20 mm free stock.'],
 ['Controls','Use the actual third side-switch actuator solid and separate it from the fixed housing.','Corrected concealed side-drive geometry retained. Four fresh 0.05 mm sweeps reach the actual plungers with no surrounding-part clashes.'],
 ['Light and microphone','Keep the OEM optical/acoustic location and mounting corrections.','Final LED saddle/coupler and microphone alignment retained. Round light output moves from Y5 to Y2; original collector stays at Y5.'],
 ['Fasteners','Use the final countersunk hardware, staged access, blind-floor and engagement checks.','18 final fasteners retained; all driver approaches clear. Matching thread-region permission is narrow and does not mask head/off-axis collisions.'],
 ['Casting adaptation','Carry the UC1 local release approach into the final R2 geometry.','16 Fusion-cut 1-degree boss tapers; 0.10 mm root lands. Speaker Y18/66 and rear LTE tip Z=-20.33 are respected. Not global injection-mold draft.'],
 ['Assembly and attachment','Check the completed 28 geometry rather than inheriting a source audit result.','25 cover-insertion samples clear. The contact graph identifies 19 bodies in control/clamp/switch groups without a zero-gap path; specified threaded mounting, 60 OEM restraint checks and 24 key-capture checks address these separate mechanisms. Physical forces remain unqualified.'],
 ['USB mating','Keep the receiver-reference conflict visible until the actual plug datum is known.','Case approach clear at 7 samples; receiver solid 227 overlaps the conservative gauge by 2.484173 mm3 at assumed full seating. Open physical/mating-datum hold.']
]
result={'taskUrl':'https://adam.new/jacob-catalano/tasks?task=da122c5a-e392-47b7-a53f-a52d949eabb7','reviewMethod':'Read existing task chat and downloaded existing completed output in browser. No Adam MCP, generation or credits used. All 28 CAD authored in desktop Fusion.','final27PackageSha256':'c12f00178166087ff6ff732d757e157be37ae16e3b6b2cc16dea96d06405adc1','baselinePreservedBodies':436,'rigidBodyMm':[78,150,24],'customComponents':73,'fasteners':18,'caseSolids':182,'referenceSolids':540,'nominalChecks':{'staticUnintended':len(st['unintended']),'retentionDirectionsPassed':sum(x['blocked_within_1_2mm'] for x in rt),'retentionDirectionsChecked':len(rt),'controlSweepsPassed':sum(x['cad_sweep_clear']for x in mo),'coverPositionsClear':len(cv['samples']),'fastenerApproachesClear':len(fa),'bodiesWithoutZeroGapContactPath':attach['unconnected'],'controlCaptureDirectionsChecked':len(capture['checks']),'USBCaseSamplesClear':len(usb['samples'])},'holds':['USB full-mating datum / actual plug','lens collector press fit','offset optical output uniformity','pad preload and switch return/overtravel','casting materials, shrink and release','mesh/scrim acoustic loss, adhesion and rattle','RF, harness, sealing and durability'],'appliedSteps':[dict(zip(['area','traceLesson','appliedTo28'],r))for r in updates],'checkedFiles':{str(p.relative_to(R)):sha(p)for p in sorted((R/'cad').rglob('*'))if p.is_file()and not p.name.startswith('Concept_28_R1_')},'fabricationRelease':False}
(A/'trace_reconciliation.json').write_text(json.dumps(result,indent=2))
with(D/'Trace_Reconciliation.csv').open('w',newline='')as f:
 w=csv.writer(f);w.writerow(['Area','Relevant completed-trace lesson','Applied to 28 / result']);w.writerows(updates)
text='''# Concept 28 R1 - final trace reconciliation

The existing [completed Version 27 task](https://adam.new/jacob-catalano/tasks?task=da122c5a-e392-47b7-a53f-a52d949eabb7) was read in the browser. Its existing final output was downloaded, inspected and compared with the earlier published checkpoint. No Adam MCP or new generation was used. Version 28 was authored in desktop Autodesk Fusion.

Final 27 package SHA-256: `c12f00178166087ff6ff732d757e157be37ae16e3b6b2cc16dea96d06405adc1`.

The final source contains 67 custom/prepared parts and 18 fasteners. Version 28 changes six cosmetic parts and adds six grille-stack components, yielding 73 custom/prepared parts, 18 fasteners, 182 CASE solids and 540 full-reference solids. The full reference includes 356 OEM solids and two nominal lead routes. The 92 mesh rods represent one purchased weave panel.

## Relevant steps applied

'''
for area,lesson,applied in updates:text+=f'### {area}\n\n{lesson} {applied}\n\n'
text+='''## Fresh evidence and limits

All 91 individual STEP exports are valid. Native Fusion verifies zero bidirectional material difference in the front-shell interior below Z=-2.21 versus the casting-adapted final baseline, and unchanged faces, volumes, bounds and transforms for 436 retained assembly-occurrence bodies. Coincident-face volume integration varies slightly across imports; preservation uses native bidirectional differences, not a volume-only comparison.

There are no unintended static interferences above the audit threshold. The inherited lens collector has a 0.592018 mm3 nominal press-fit interference requiring physical fit approval. All 60 sampled directional retention checks are blocked within 0.50 mm; this is geometry, not load or shock qualification. All four control sweeps are clear and reach their actual plungers; force, return and permissible overtravel remain unqualified. All 25 rear-cover positions and 18 staged driver approaches are clear. Both antenna service frames have clear sampled lifts. The zero-gap attachment graph leaves 19 bodies in the control, clamp and switch groups disconnected because running clearances and simplified threads do not form a continuous touching network. These are not counted as a contact-graph PASS: threaded mounting, six-axis OEM restraint and all 24 key-capture trials are reported separately. Actual clamping, key return and retention forces remain first-article tests.

The USB gauge is not an actual vendor-qualified plug. The 2.484173 mm3 receiver-reference overlap remains an explicit hold, not a PASS. Obtain a real plug and confirmed mating datum before approving this interface. Do not alter OEM PCB geometry to hide it.

The manufacturing route remains supplier-reviewed urethane casting with separate metal/mesh, optical, PA12 and soft-stock processes. Nominal casting masters contain no supplier shrink scale, mold splits, gates or vents. Physical first articles must qualify resin shrink/release, threaded pilots, pad forces, switch feel, optics, acoustics, RF, bonds, lead routing and durability.

The website, diagrams and exported CAD refer to this same checked build. Source inventories and SHA-256 manifests accompany the files. Earlier 27 options remain available independently.
'''
(D/'Trace_Reconciliation.md').write_text(text)
print(json.dumps(result['nominalChecks']))
