Compare commits

...
Author SHA1 Message Date
michele 29e1a3033d Leave USB-C vSafe UNKNOWN; AF zip has no USB-IF PD (2.83.0).
Alta Frequenza / af-allegati only hold TI SI (SNLA027B, SDAA499), which do not state vSafe5V/vSafe0V. CabCon R2.5 §1.6 defers volts to USB PD. HDMI 1.4 TMDS stays UNKNOWN.
2026-09-22 18:38:33 +02:00
michele bb83f63114 HDMI 2.0+ TI layout uses source_type VENDOR (2.82.0).
Add VENDOR to SourceType. HDMI 2.0/FRL fill TMDS1204 PCB numbers as VENDOR RECOMMENDED; TMDS1204-specific skew/vias/data_rate/SIGDET stay PHY_DEPENDENT. HDMI 1.4 TMDS remains UNKNOWN. Not HDMI Forum STANDARD.
2026-09-22 18:25:26 +02:00
michele 3c0b3e14dc Archive protocol PDFs on disk; HDMI 2.0/FRL TI layout as VENDOR (2.81.0).
INDEX.md lists cites. PDFs gitignored. HDMI 1.4 TMDS Zdiff stays UNKNOWN. pcbsync not packed.
2026-09-22 18:18:03 +02:00
michele 1455e974ac Add TI TMDS1204 HDMI layout as VENDOR/PHY only (2.80.0).
Sink/source ZPCB, skew, length, vias from SLLSF57A Tables 8-6/8-2. Generic hdmi-* TMDS Zdiff stays UNKNOWN. SLLA633 is SIGDET only.
2026-09-22 18:12:23 +02:00
michele 25aa608052 Fill HDMI CEC electrical from HDMI Specification 1.3 (2.79.0).
27 kΩ pull-up, VOL/VOH, 200 pF device / 700 pF cable, 5 Ω interconnect. TMDS/FRL Zdiff stays UNKNOWN.
2026-09-22 18:07:52 +02:00
michele d32af5627a Fill 1000BASE-T from IEEE 802.3-2012 Section Three Clause 40 (2.78.0).
Cable 100 Ω / 100 m / 570 ns / 50 ns skew stay CABLE. MDI 16 dB and 0.67 V are PHY. L2 PCB Zdiff UNKNOWN. 1000BASE-X 1000 Mb/s from Clause 36.
2026-09-22 18:03:44 +02:00
michele 8a93ffc1c5 Fill 10BASE-T numbers from IEEE 802.3-2015 Section One Clause 14 (2.77.0).
Cable 100 Ω / 100 m / 11.5 dB stay CABLE. L2 PCB Zdiff UNKNOWN. 1000BASE-T not in this volume.
2026-09-22 18:00:10 +02:00
michele 421f659054 Fill Type-C VBUS and CC holes from CabCon R2.5 and R2.0 (2.76.0).
R2.5 keeps Rp/Rd/Ra, charger 4.75/4.0 V, zOPEN, tCCDebounce, tVBUSON.
R2.0 August 2019 Table 4-32 fills Source CC shall-detect only. vSafe5V stays UNKNOWN.
2026-09-22 17:55:47 +02:00
michele c4cd046ea9 Fill USB 2.0 Rev 2.0 and Type-C CabCon R2.5 numbers (2.75.0).
LS/FS rates, pull-up/down, and VBUS come from the base spec. Cable Z0 90 ohm is CABLE; PCB should 90 ohm is RECOMMENDED. L2 differential_impedance stays UNKNOWN. Rp/Rd/Ra from CabCon Tables 4-27/28/29. IEEE Section One/Three and HDMI still missing. PDFs not in git.
2026-09-22 16:53:49 +02:00
michele f3be485b75 Fill protocol packs from recovered USB CTS, Type-C FTS, DVI 1.0, and IEEE 802.3-2012 Section Two (2.74.0).
NUMERIC rows cite document title, revision, section/table, and page. USB Zdiff, Type-C Rp/Rd, 10BASE-T, and 1000BASE-T stay UNKNOWN. PDFs are not in git.
2026-09-22 14:43:26 +02:00
michele 949f5f1541 Add protocol-certification M6/M7 USB-C Ethernet HDMI packs (2.73.0).
USB 2.0 is protocol, Type-C is connector, USB 2.0 over Type-C is the
implementation. Ethernet/HDMI skeletons stay UNKNOWN with needed_document.
No invented ohms; Mini HDMI is connector-only; RJ45 is not 1000BASE-T.
2026-09-22 13:40:37 +02:00
michele 7baffadd6b Add protocol-certification M10 catalog skeletons (2.72.0).
PCIe/CXL keep logical vs physical ids. I2C, CAN, RGMII and missing
high-speed processor interfaces get required_checks; numbers stay
UNKNOWN/MISSING_SOURCE until an official cite. No invented ohms.
2026-09-22 13:03:48 +02:00
michele 866c2e9242 Add protocol-certification M9 L3 channel certifier (2.71.0).
L3 CHANNEL structure for timing budget, insertion loss, return loss,
crosstalk, and complete channel. Numeric PASS/FAIL only from existing
channel FACT; otherwise a visible skip. No OpenEMS, no invented S-parameters,
no M6 packs.
2026-09-22 12:58:18 +02:00
michele 14272d7446 Add protocol-certification M8 DDR instance grouping (2.70.0).
Controller-aware per-memory instances, DQ/DQS vs addr/cmd/ctrl/ck, HBM not classic DDR PCB DQ. No universal mm/ps. No M6 packs, no L3 solver.
2026-09-22 12:46:01 +02:00
michele 24c4beecc9 Add protocol-certification M5 Protocolli report UI (2.69.0).
Instances, L0–L3 max level, measured/limit/margin/source/method, traceability chain. FAIL listed first, not under Warning. Visible skips. No pack numbers, no L3 solver.
2026-09-22 12:37:31 +02:00
michele 0848eb8416 Add protocol-certification M4 L2 electrical certifier (2.68.0).
Z/termination/levels from datasheet, stackup, fab, or cited pack only. Never invented USB ohms. No L3/OpenEMS. L0/L1 are not electrical.
2026-09-22 12:30:13 +02:00
michele 10d21cdc80 Add protocol-certification M3 L1 geometric certifier (2.67.0).
Length, topology, vias, stubs, layer, grouping. Skew only vs NUMERIC mm or DESIGN LIMIT. No invented ohms/mm/ps. Not electrical. No L2/L3.
2026-09-22 12:22:18 +02:00
michele 3cc2e5469b Add protocol-certification M2 L0 structural certifier (2.66.0).
Presence and connection only. FAIL solely on missing MANDATORY structure.
AXI4 internal is NOT_APPLICABLE, not FAIL. RECOMMENDED never FAIL. No L1–L3
and no invented ohms/mm/ps.
2026-09-22 12:12:25 +02:00
michele fc6524a2a9 Add protocol-certification M1 instance recognition (2.65.0).
physical_bus_instance from declaration, silicon/part, pin/net names, and
pairs. USB and DDR fixtures emit groups; AXI4 internal attaches no PCB
nets. Ambiguity is REVIEW, not FAIL. No L0–L3 certifier and no invented Z.
2026-09-22 12:04:37 +02:00
michele 36ad979612 Add protocol-certification M0 catalog, loader, and empty report (2.64.0).
Versioned JSON skeletons without invented ohms/mm/ps. RECOMMENDED is not
FAIL-mandatory; typical-as-standard is rejected. Report Protocolli is empty
until recognition (M1+). Native src overlays inherited periscopex on the
package path.
2026-09-22 11:57:26 +02:00
michele c87adf11a9 Add AF trace analysis after PCB checks (2.63.5).
Trigger λ/10 and tr/(6 tpd) from FACT; pairs analyzed together; Z only from
datasheet; visible INSUFFICIENT skips; lossless RLGC cascade (no OpenEMS).
2026-09-22 08:39:37 +02:00
michele 8b4f7710cf Show Error groups with max child severity (2.63.4).
PCB tree folders are Error / Warning / Info. U18 with PE-PLC-002
ERROR is ERROR, not WARNING. J2 and other connectors list with ICs.
PE-PLC stays in the PCB exam bucket. No deploy.
2026-09-22 01:04:08 +02:00
michele 8f434ffd31 Skip module-die and truncated QFN pintable false PE-BOM hits (2.63.3).
WROOM lands are not the ESP32 die table (U11). QFN-48 pads 25–48 are
not extras when extraction stopped at 1–24 (U12). VQFN is the QFN
family (U19 24-QFN 4×4). Real extra signal pads still ERROR.
2026-09-22 00:57:57 +02:00
michele cd7a7ca3a6 Join PE-BOM-011 pins by name, not pin_count (2.63.2).
USB-C A5/B5 are contacts, not EP. Datasheet pintable, KiCad
.kicad_mod, and embedded PCB pads join by pin identity. Missing
pintable skips; scalar pin_count is never an ERROR authority.
2026-09-22 00:47:58 +02:00
michele 6b751522b7 Keep rust-criteri and conformita-coding in the local docs tree.
Absolute paths in the headings so the files open from
~/Development/periscope/docs. PCB 2.62.1 check list unchanged.
2026-09-21 22:40:12 +02:00
michele 6d9d21a023 Register library components from a datasheet without an exam (2.63.1).
POST /api/library/datasheets now writes an IC inbox card or a
passive/discrete model. Empty pintables never enter library/extracted.
AF Board+AI runs after unchanged run_pcb_checks (PE-SI / HF line stay).
2026-09-21 22:33:30 +02:00
michele 4df04df5d4 Make the component library a standalone product door (2.63.0).
Add /api/library datasheet import and component GET/PUT with no exam.
Reorganize pytest into datasheet, library, schematic, PCB, and AF+AI.
Document Rust criteria (none chosen; no rustup) and coding conformity.
2026-09-21 22:12:00 +02:00
michele 20733f0ec6 Add remaining PCB analysis checks to run_pcb_checks (2.62.1).
Phase B: stackup vs fab spec, via current with datasheet I (no IPC via
chart), ESD pad distance, USB-PD, PoE isolation voltage, antenna, and
PDN Z(f). Skip without evidence. Not DRC or FEM.
2026-09-21 20:49:21 +02:00
michele 69d5dd9313 Add HF line and bus analysis to run_pcb_checks (2.62.0).
Phase A: stub, return-split, and BOM termination on buses present on the
graph; DDR/CPU/FPGA class certifiers only when that device exists. Skip
without evidence. Via, pad, track, and zone stay distinct. Not DRC or FEM.
2026-09-21 20:42:55 +02:00
michele 309644e654 Rewrite README as Periscope PCB-analysis product copy.
Replace the schematic-only DeepSeek scaffold with what this tree actually is: full board analysis for fab, gated interface certifiers, evidence rules, and the run/Docker/update commands that exist on disk.
2026-09-21 17:51:41 +02:00
michele bd3a6fd009 Gate interface certifiers to connectors on this board (2.61.2).
USB-C/RJ45/PoE/DDR3 are the method, not a catalog. No connector means
no finding. Bare RJ45 is Ethernet only; PoE needs PoE evidence. HubAudio
has USB-C and PoE MagJack, not DDR. Skip-I unchanged.
2026-09-21 12:24:54 +02:00
michele c6abdae762 Skip PE-PWR/PE-VIA without datasheet current (2.61.1).
Trace-width vs current runs only with I_load/Imax/I_abs. Missing I is a
skip, not INFO INSUFFICIENT, not USB 500 mA, not Iout_max-as-load.
2026-09-21 12:11:52 +02:00
michele 6dc04b5cc7 Add USB-C, Ethernet, and PoE interface class certifiers (2.61.0).
Dedicated deterministic engines certify class and connection integrity
(CC1/CC2, Rd 5.1 kΩ, VBUS/GND, SuperSpeed if USB3; 10/100 vs GbE
magnetics; PoE only with evidence). Missing evidence is INSUFFICIENT
or N/A, never invented PoE, SuperSpeed, Z, or I. No FEM, no via IPC.
2026-09-21 11:52:44 +02:00
michele 07ad5c72fa Fix PCB software false positives (2.60.11).
KiCad 9/10 name-only nets fill the index. PE-LAY-004 counts tracks, vias,
and pours and skips NC nets. Missing I_load is INSUFFICIENT. EP pads are
not PE-BOM-011; abs-max binds the named pin. Kelvin/EMI/PI ignore NC and
IN±. LQW decodes nH; BLM/FB is a bead, not DCR as Z.
2026-09-21 11:06:38 +02:00
michele 0d817c876f Echo DeepSeek thinking reasoning_content on the next turn.
HubAudio U11/U12/U38 400'd after a thinking-only review turn because
the retry dropped reasoning_content. Native client now appends that
field and continues; hierarchical sheet ingest stays in 2.60.10.
2026-09-21 09:11:37 +02:00
michele 348f390cce Ingest hierarchical KiCad sheets; still skip .history.
Apri progetto collects every *.kicad_sch beside the .kicad_pro and
follows Sheetfile/(sheet)/file= into a subfolder. .history, .git, and
backups are not walked. Not only HubAudio.kicad_sch.
2026-09-21 08:28:49 +02:00
michele 027546b0bd Stop hanging after KiCad folder permission.
Apri progetto walked every nested file (HubAudio .history ~2000) so
onFilesChange never ran and Next stayed disabled. Read only kicad_pro,
sch, and pcb in the project dir; timeout to an error; enable Next when
.kicad_pro is in.
2026-09-21 08:18:01 +02:00
michele a0b89365c2 Type directory picker without DOM FileSystemDirectoryHandle.entries. 2026-09-21 08:00:08 +02:00
michele 278f176859 Open a real folder picker for Apri progetto KiCad.
The Mac Carica dialog was a file input (accept empty, no working
webkitdirectory). Use showDirectoryPicker or a hidden input with
webkitdirectory=true and no accept. Ignore empty/cancel picks.
2026-09-21 07:59:06 +02:00
michele fbf2fc87a6 Detect HubAudio.kicad_pro from folder pick, not only File.name.
Safari/macOS often puts .kicad_pro on webkitRelativePath while name is
the stem. Match both, sniff JSON if the suffix is missing, and set
webkitdirectory on the input DOM so the folder picker actually recurses.
2026-09-21 07:54:35 +02:00
michele bfb781f94f Open a KiCad project folder: schematic + PCB, no netlist.
Apri progetto KiCad picks the folder that contains .kicad_pro and loads
sibling hierarchical sheets and the matching .kicad_pcb. Connectivity and
MPN/PNM/Value come from the schematic; a leftover PADS .asc is ignored.
A lone .kicad_pro upload is rejected unless that path exists on disk.
2026-09-21 07:26:01 +02:00
michele ec2ffd6107 Join KiCad hierarchical PNM/MPN when the BOM CSV omits a designator.
Child-sheet symbol fields fill graph mpn; empty sheet fields stay empty. A sibling .kicad_sch next to a PADS netlist is used the same way.
2026-09-21 01:56:13 +02:00
michele 82d185ccf4 Treat KiCad PNM as MPN and skip missing U* as INSUFFICIENT_EVIDENCE.
HubAudio CSV has no U13–U39 rows; those refs stay without an invented part number. IC Value fills MPN when PNM is blank. Progress no longer labels netlist-only ICs as “no MPN in BOM”.
2026-09-21 00:53:06 +02:00
michele e31981c812 Persist recovered ferrite Z by comparing against the raw JSON.
ComponentModel validation already fills impedance from quoted ohm@freq, so snapshotting the in-memory specs skipped the write.
2026-09-21 00:33:17 +02:00
michele 72bcab50a1 Fill ferrite bead impedance from the MPN datasheet PDF.
graph_build searches project uploads and library blob refs, persists recovered Z, and still loads when the PDF has no impedance. Ohms are not written to henries.
2026-09-21 00:29:12 +02:00
michele a2d5900b64 Recover ferrite bead Z from datasheet evidence without aborting graph_build. 2026-09-21 00:19:06 +02:00
michele 51c09b2176 Point Emmaforo note at completed HubAudio MODE=pcb wall. 2026-09-20 23:54:21 +02:00
michele 9a2320f9e2 Record HubAudio MODE=pcb wall times including DeepSeek AI. 2026-09-20 23:54:09 +02:00
michele 8040686e8b Allow ferrite beads without impedance_ohm to load.
Missing Z is optional, not invented. graph_build skips bad models
instead of aborting. Other inductors still require value_henries.
2026-09-20 23:08:33 +02:00
michele 63c85a4319 Point Emmaforo timing note at HubAudio measured seconds. 2026-09-20 23:00:27 +02:00
michele 6b605d1cf2 Record HubAudio PCB parse, Z0, and checks wall times. 2026-09-20 23:00:09 +02:00
michele a001971248 Note HubAudio PCB timing: no stored .kicad_pcb, LLM not timed. 2026-09-20 21:31:17 +02:00
michele 39169b33b8 Note live Emmaforo PCB exam wall times (parse, Z0, checks, AI).
Read-only docker exec on stored pcb.kicad_pcb. No pipeline change, no deploy.
2026-09-20 21:27:27 +02:00
michele 7a32c552bb Stamp 2.60.0 incomplete PCB exam and owner project delete.
Partial layouts still use MODE=pcb. Missing copper is INSUFFICIENT or
skipped, never Euclidean stand-in tracks. Via≠Pad unchanged. DELETE
/api/projects/{id} is owner-only with a dashboard confirm dialog.
2026-09-20 21:17:26 +02:00
michele ed3fff565d Stamp 2.59.0 Docker leftover seams only, not PinScope product.
Images copy periscope/src, vendor/, and skipped Clerk/shadcn/billing/GCS
files. dependency/ stays in git. Audit written; FastAPI boots with
PYTHONPATH=src.
2026-09-20 21:03:26 +02:00
michele 22bc075c58 Stamp 2.58.0 native JWT middleware and useAuthApi.
Same skip paths, Bearer/query token, Clerk RS256 leftover, and local HS256
contract. routers/auth.py, user records, and AUTH_JWT_SECRET are untouched.
2026-09-20 21:01:51 +02:00
michele 3a666ea8ae Stamp 2.57.0 native package.json, requirements, and unused Docker copies.
Frontend periscope-web manifests, pip requirements, and EDA logos/examples
overlay from src. Docker installs from those files. Unused PinScope public
blobs are dockerignored. Landing png/gif stay in dependency until native
captures exist.
2026-09-20 21:00:21 +02:00
michele 7a377889ae Overlay live legal and changelog markdown from periscope/src.
privacy, terms, file-guide, and changelog stay Periscope operator text at 2.56.0. Docker copies src changelog last; the frontend image keeps content/ at runtime.
2026-09-20 20:37:11 +02:00
michele 6b1fe5be00 Stamp 2.56.0 after native taxonomy and skills overlay.
Compose mounts src/taxonomy. Local DeepSeek skills; no Console upload.
2026-09-20 20:31:50 +02:00
michele 00e5df8a36 Overlay app favicon.ico from the Periscope mark.
Replaces the leftover OSS Next.ico so /favicon.ico matches favicon_io.
2026-09-20 20:30:36 +02:00
michele ee160a5df9 Overlay native taxonomy JSON and local DeepSeek skills.
repo_paths and compose mount src/taxonomy first. Docker copies dependency then src for taxonomy and skills. SKILL.md prose is rewritten; schema IDs and validate contracts stay. Manifest 1.14.0. Do not run upload_skills.py.
2026-09-20 20:30:25 +02:00
michele 28a4dc8255 Stamp 2.55.0 after Next config and CSP overlay rewrite.
package.json stays inherited. Legal markdown and changelog remain in dependency.
2026-09-20 20:20:49 +02:00
michele 6f3e714a54 Rewrite CSP host seam and middleware package marker.
Export names stay for the cloud overlay. JWT still lives only in inherited auth.py.
2026-09-20 20:19:58 +02:00
michele 739e6f7f17 Rewrite Next, ESLint, PostCSS, and tsconfig overlay.
CSP, login/register redirects, pdfjs-dist externals, and canvas alias stay the same. package.json is unchanged.
2026-09-20 20:19:37 +02:00
michele cdfe5812cf Stamp 2.54.0 after leftover frontend widget rewrite.
PDF sheet, theme, upload zone, reviewed hooks, and globals.css overlay from periscope/src.
2026-09-20 20:13:44 +02:00
michele 44e86e258e Rewrite app color tokens and fade-up animation.
Tailwind/shadcn imports, light/dark oklch values, and .animate-fade-up stay the same so layout does not shift.
2026-09-20 20:12:54 +02:00
michele 72b4b20665 Rewrite reviewed-finding localStorage hooks.
Dashboard count and report toggle still migrate legacy keys and skip the first persist write.
2026-09-20 20:12:20 +02:00
michele 7d82358e19 Rewrite project file drop zone.
Folder drops still skip KiCad backups/pretty/3dmodels; dashed upload chrome is unchanged.
2026-09-20 20:11:48 +02:00
michele c5cd98587f Rewrite class-based theme provider and toggle.
next-themes still defaults to dark with no system follow. Clerk theme wrapper stays inherited.
2026-09-20 20:11:20 +02:00
michele b3566db828 Rewrite datasheet PDF sheet overlay.
Right-side Sheet still mounts PdfViewerPanel only while open; shadcn Sheet stays imported.
2026-09-20 20:11:00 +02:00
michele d4070081c8 Stamp 2.53.0 after site, legal, OG, and BFF rewrite.
Excel export headers are mutable for tsc. Changelog and APP_VERSION match the native frontend overlay.
2026-09-20 20:06:15 +02:00
michele 292d2e2077 Rewrite Next.js local BFF routes and mock catalog.
Projects, report, and graph JSON handlers overlay from periscope/src. Clerk proxy stays the inherited open-core seam.
2026-09-20 20:04:04 +02:00
michele 93f6fad3e7 Rewrite legal page shells and Open Graph images.
Overlay legal markdown chrome, changelog timeline, EDA file-guide tabs, and OG/Twitter images from periscope/src instead of inherited PinScope copies.
2026-09-20 20:02:57 +02:00
michele a9ce71f17a Rewrite frontend site identity, version stamp, and Excel export.
Changelog remains the source of APP_VERSION via overlay sync-version.mjs.
2026-09-20 20:00:15 +02:00
michele d21a303e8b Stamp 2.52.0 after leftover frontend rewrite.
App and marketing pages overlay from src. Auth and billing seams unchanged.
2026-09-20 19:53:58 +02:00
michele a011351828 Rewrite leftover frontend pages into src overlay.
Dashboard, project, report, progress, admin, feedback, and marketing
keep routes and layout. Billing/Clerk/analytics stay imported seams.
2026-09-20 19:53:33 +02:00
michele 2613678442 Rewrite frontend types and HTTP client in src.
Export names match the leftover pages. Billing HTTP wrappers stay so
gateway seams are not restyled here.
2026-09-20 19:41:15 +02:00
michele bac75a2fba Stamp 2.51.0 after native app leftover rewrite.
Settings, FastAPI entry, worker, and leftover routers now resolve from
src. Auth router and JWT middleware are unchanged.
2026-09-20 19:32:50 +02:00
michele d0fd37c1b5 Rewrite leftover HTTP routers except auth.
Project ingest, pipeline enqueue/SSE, reports, admin, contact, survey,
and feedback now resolve from src. Auth router is unchanged.
2026-09-20 19:31:41 +02:00
michele 7c3c7d17d8 Rewrite FastAPI app and pipeline worker entrypoint.
Worker still refuses to import backend.main. Auth router is mounted
unchanged; CORS stays outermost so 401s keep headers.
2026-09-20 19:23:33 +02:00
michele d0bbd582a8 Rewrite Settings as native Periscope config.
DeepSeek remains the only live provider; leftover Anthropic env names
are coerced or ignored. Skills manifest is resolved across the split tree.
2026-09-20 19:21:52 +02:00
michele 40b251c387 Stamp 2.50.0 after pipeline and leftover analysis rewrite.
Full pytest is green. Inherited copies stay on disk; auth untouched.
2026-09-20 19:14:50 +02:00
michele 82ffa755cd Rewrite leftover analysis modules imported by src.
validate/validation_tools alias native lookup and review tools. Passive
resolve, derating, BOM summary, pin-mux, LED current, and net-function
tokens are original Periscope code. finding_engine and pcb_* unchanged.
2026-09-20 19:14:20 +02:00
michele 3d7fa21eb6 Rewrite analysis pipeline, projects, email, and LCSC client.
Native job_workspace / datasheet_extract / review_session stay the live
BOM-extract-graph-review path. Project writes follow owner_user_id.
2026-09-20 19:10:28 +02:00
michele 6a4903fa3a Rewrite job_runner, event_bridge, cost estimator, and DigiKey client.
Local pid-file dispatch stays the self-host path. DigiKey still rejects unrelated MPNs. Inherited copies remain on disk.
2026-09-20 18:57:58 +02:00
michele e240afce23 Rewrite leftover LLM factory (DeepSeek-only), storage, validation.
Anthropic/Gemini names resolve to DeepSeek. Extraction import path re-exports datasheet_extract. Inherited copies stay on disk. storage_gcs unused, skipped.
2026-09-20 18:55:18 +02:00
michele 572b8d24f3 Rewrite normalize, cross-IC dedupe, and billing seam (2.49.0).
Downgrade-only clamp and fail-soft coverage stay in src. Inherited copies remain on disk. Self-host billing is NullBilling.
2026-09-20 18:47:45 +02:00
michele fe89851c10 Rewrite taxonomy loader; JSON path via repo_paths (2.48.0).
TAXONOMY_DIR is taxonomy_dir() so src reads dependency/taxonomy until a src tree exists. Inherited taxonomy.py stays on disk. Changelog covers models, parsers, and taxonomy.
2026-09-20 18:41:12 +02:00
michele 9997f39718 Rewrite PADS/BOM dispatch and EDIF ingest as Periscope parsers.
KiCad schematic parser and PCB via≠pad parser stay native. Inherited
parser files remain in dependency/.
2026-09-20 18:38:26 +02:00
michele 24f9c952e2 Rewrite Periscope models.py with disjoint layout primitives.
Pad, via, track, and zone stay separate types. Inherited models.py remains
in dependency/. Public graph/finding fields are unchanged.
2026-09-20 18:37:03 +02:00
michele 19a1eef936 Record 2.47.0 native graph rewrite in changelog and independence plan. 2026-09-20 18:32:47 +02:00
michele 7ff049f6d0 Rewrite DesignGraph builder as original Periscope graph.py.
Src module classifies refs, infers net type/voltage, and prefers board nets
when a .kicad_pcb is present. PinScope graph.py remains in dependency/.
2026-09-20 18:32:36 +02:00
michele 5a1d31ce7b Revert PinScope overlay copies from periscope/src (2.46.0).
Remove stamped near-identical modules so inherited code loads from
dependency/ again. Keep native finding engine, PCB/placement, review,
job workspace, datasheet extract, via-vs-pad parser, logo, and local JWT.
2026-09-20 18:30:21 +02:00
michele 2f2e35e802 Replace paraphrased constitution with the 1224-line master.
Copy CODING_CONSTITUTION.md from the AgentStore docs/development path and split
the seven always-on .mdc files from that exact text.
2026-09-20 18:24:29 +02:00
michele 0533d4ebd2 Add Periscope Cursor engineering constitution and always-on rules.
Docs-only: master CODING_CONSTITUTION plus seven .mdc splits. Git policy is
phase = test then commit+push; deploy only after a macro-phase.
2026-09-20 18:06:00 +02:00
michele 6d6e70cec0 Overlay leftover FastAPI entry, routers, and jobs into periscope/src (2.45.0).
Copy main, config, middleware/auth, leftover routers, pipeline_worker,
job_runner, event_bridge, projects, and admin_settings without deleting
dependency copies. Native auth and impedance routers stay as-is.
2026-09-20 17:39:15 +02:00
michele 49a27d5951 Fix leftover service overlay stamps so __future__ stays first.
Use comment headers instead of a second module docstring so overlay copies remain valid Python.
2026-09-20 17:21:57 +02:00
michele 0b01617b37 Overlay leftover services and LLM factory into periscope/src (2.44.0).
Copy api_logs, findings normalize/dedupe, billing_hook, datasheet_store,
cost_estimator, storage, purple_parts, email, digikey, and llm factory/types/base
without deleting the inherited dependency copies.
2026-09-20 17:15:55 +02:00
michele 1389d832df Overlay leftover PinScope modules src still imported.
utils, resolve_passives, derating, bom_summary, pin_mux, LED current,
pin-function tokens, plus live analysis validate/validation_tools/pipeline/
validation/extraction, skills, and taxonomy JSON now resolve from
periscope/src. Inherited copies stay in dependency/. repo_paths prefers
src then /app; Docker copies src taxonomy/skills last.
2026-09-20 16:56:20 +02:00
michele 31fd389b38 Native overlay of graph, parsers, models, taxonomy; Periscope mark.
Src-first imports now load graph/parsers/EDIF/models/taxonomy from
periscope/src. Inherited copies stay in dependency/. Taxonomy JSON path
uses repo_paths. New periscope/lens mark at existing 16/32/180/192/512
favicon sizes; header uses PeriscopeMark instead of the lucide CPU glyph.
2026-09-20 16:41:50 +02:00
michele 34a9b30a35 Re-parse .kicad_pcb on PCB exam instead of stale layout_graph.
Cached layout_graph still listed stitching via-pads as component pads,
so PE-BOM-011 kept firing after the ingest fix. PCB/placement jobs now
parse the board file and refresh the cache.
2026-09-20 16:16:46 +02:00
michele 09c49f8529 Resolve board via nets by net code, not pad-net token.
_via_from_node used _pad_net first, so (net 1) stayed as '1' instead of GND.
2026-09-20 16:06:54 +02:00
michele ad21d00cd0 Fix PE-BOM-011: classify footprint vias as vias, not pads.
KiCad stitching/thermal vias inside a footprint are (via) or copper-only
thru_hole (pad) objects. parse_kicad_pcb was appending every (pad) to
LayoutFootprint.pads, so PE-BOM-011 compared datasheet pin_count to via
numbers. Nested vias join LayoutGraph.vias; soldered THT pads stay pads.
2026-09-20 16:06:10 +02:00
michele 19eab09000 Native PipelineWorkspace and event broker in periscope/src.
PCB and placement jobs import job_workspace instead of PinScope
pipeline.py. Analysis run_pipeline re-exports the same broker singleton.
2026-09-20 15:34:41 +02:00
michele 5c0c5184fb Native DeepSeek datasheet extraction in periscope/src (Fase C3).
Pipeline and LCSC resolve call datasheet_extract; inherited extraction.py
stays in dependency as fallback. No Anthropic Console skill ids.
2026-09-20 15:26:21 +02:00
michele a96ee2e88a Stop periscope/src importing PinScope validate.py after live C2 smoke.
PCB review and src checks use native parse, constraints lookup, and
review_session. Inherited validate.py and validation_tools.py stay in
dependency/.
2026-09-20 15:21:32 +02:00
michele 974923b2e6 Native DeepSeek review loop in periscope/src (Fase C2).
Live review_ic_async comes from review_session; PinScope validate.py and
validation_tools.py stay in dependency as _inherited_review_ic_async fallback.
2026-09-20 15:14:21 +02:00
michele a0a2f5bdbf Fix DeepSeek-only tests after env file moves to the repo root.
Give the routing tests a dummy key so they do not require a live .env.
2026-09-20 14:33:23 +02:00
michele c362ef8a56 Split native Periscope (periscope/src) from inherited PinScope (periscope/dependency).
Keep validate.py and the finding engine as-is. AGPL LICENSE stays at the repo root.
Docker overlays dependency then src. Do not delete the inherited tree.
2026-09-20 14:31:42 +02:00
michele 0a75e5971a Gate PCB SI not_reviewed to board ICs, not the shared library.
Emmaforo listed 20 stale 1.5–1.7 MPNs (LAN8720A, W25Q, …) as
not reviewed while the four BOM ICs were already extracted and reviewed.
2026-09-20 14:05:03 +02:00
michele 312057b6d3 Gate SI layout_rules to the quoted bus, not EN RC onto USB.
PE-SI-009 no longer treats ESP32 CHIP_PU/EN RC as a USB series R.
USB without a library Z number stays PE-SI-010 measurement-only.
Pintable skill 1.13.0 requires net_class on SI kinds (usb2/usb3/MDI/RGMII/DDR3).
2026-09-20 13:13:19 +02:00
michele a63e5bd7ab Fase A identity on PCB HEAD: operator fence, keep BOM/SPOF/EMI.
Replace Faradworks Inc. TOS/privacy/contact/metadata with Michele Bigi.
Dual-read pinscope_* keys; write periscope_* only. AGPL LICENSE and
GitHub fork parent unchanged. validate.py not edited.
2026-09-20 12:41:17 +02:00
michele 1b3529501f Ship remaining PCB plan slices: BOM chain, SPOF, EMI FACT, gated Tj.
Package/pinout/ratings mismatches, SPOF as REVIEW, EMI only with a
datasheet quote, and Tj from copper+vias+θJA when every parameter exists.
Re-extract SI layout_rules from 1.12.0; ImpedenceFinder license stays UNKNOWN.
2026-09-20 12:29:27 +02:00
michele 65a91419a2 Check ImpedenceFinder against datasheet SI rules, not a dump table.
Each layout_rules SI requirement (diff/SE Z, skew, max length, spacing,
ref plane, vias, layer, return, series R) is one PASS/FAIL/MARGIN finding
with FACT and REQUIREMENT. USB/HDMI/PCIe/ETH/LVDS/DDR only; I2C GPIO CC
and analog REGN are skipped. No invented 90 Ω.
2026-09-20 10:45:27 +02:00
michele 187605763d Treat finished PCB review as complete, not a raw SSE error.
The status watcher synthesized pcb_error with pcb_status=complete (terminal)
when the worker finished before pcb_complete arrived. Map that hatch to
pcb_complete, publish the event before flipping status, and send /pcb to
the layout report tree.
2026-09-20 10:23:53 +02:00
michele 1f3876eadc Fix findings tree TypeScript duplicate findings prop.
Spread parent props first, then override with the bucketed findings list so Next build typecheck passes.
2026-09-20 10:05:02 +02:00
michele bee6369c1d Replace findings list with a tree; filter ESD/PI false positives.
PE-ESD-001 only on J* connector–IC nets (skip NC, unconnected, VSYS/GND/3V3).
PE-PI-001 treats any capacitor on the rail, including KiCad slash prefixes, as
decoupling. Sort findings ERROR then WARNING then INFO, then RULE/RISK/REVIEW/INFO.
Report sidebar is a collapsed expand-on-click tree instead of an all-open list.
GET /report and complete_findings fail-soft and sort the same way.
2026-09-20 10:03:50 +02:00
michele 342792df2d Ship Fase B slices: hierarchy, derating bands, timing, PI, ESD/return.
ERROR stays only for RULE+MANDATORY. Hierarchy walks component→pin→net→block.
Derating is PASS/MARGIN/RISK from Vop/Vrated. Timing and PI skip without numbers.
ESD and HS return path are REVIEW, not RULE ERROR.
2026-09-20 09:35:04 +02:00
michele facbaa2305 Show Action on finding cards and inject PCB geometry into AI context.
Layout and AI findings always get action (fallback recommendation). The card
renders that sentence in the body. PCB review context now includes vias under
the footprint, copper thickness, nearby widths, courtyard, and keepout polygons.
2026-09-20 09:13:51 +02:00
michele f63c1c3411 Tighten PCB findings: actions, stitch gating, real copper.
Fill action on every finding and show it in the report. Stitch/return only
on large HS/power nets. Parse stackup thickness, arcs, and vias from the
board. IC courtyard pad copper is not PE-PLC-004 RULE. Recommended RC/cap
stay REVIEW.
2026-09-20 08:58:54 +02:00
michele 1e379f6042 Restore build_placement_plan import in the PCB pipeline.
MODE=pcb classify crashed with NameError after the finding-engine import swap.
2026-09-20 08:44:26 +02:00
michele dc65e96a22 Apply the finding engine to schematic and PCB reviews.
FACT, REQUIREMENT, and INFERENCE are separate fields; datasheet provenance
lives in the rule DB so Recommended cannot stay ERROR; LLM output is REVIEW.
Designer decisions persist across rescans. Schematic and PCB share one library
and the same finding object in the report UI.
2026-09-20 08:38:59 +02:00
michele 8f4ebc645c Share library/extracted for schematic and PCB review.
PCB AI skips a second PDF exam (pintable cache, pdf_path=None) and the report
gains a PCB exam section plus power-trace, thermal, via, Kelvin, and GND-stitch
checks grounded in board geometry and extracted specs.
2026-09-20 08:32:23 +02:00
michele f3f96ea4d1 Treat KiCad /net vs schematic net as one hierarchy finding.
Pad-net compare strips leading slash and nested sheet path so /ESP32_EN
matches ESP32_EN. If every mismatch is only that prefix, emit PE-LAY-003
once instead of per-pad reconnect errors.
2026-09-20 08:10:34 +02:00
michele 89a484830e Unstick analysis running when the worker is dead.
A container rebuild left Emmaforo status=running with no process, so
PCB start kept 409. Heal on GET now matches placement/PCB: complete if
report.json exists, otherwise error.
2026-09-20 00:59:22 +02:00
michele 3e2ba269f9 Write project.json to the storage owner prefix.
update_project used meta.user_id for the path, so JWT projects that still
have user_id=local never persisted pcb_status=queued and the PCB worker
exited as draft. Point writes at the prefix used to read the project.
2026-09-20 00:57:15 +02:00
michele 344ecb3389 Join railway-caddy network pinscope_pinscope after compose up.
Caddy reverse_proxies periscope-frontend by Docker DNS and is not on
the compose project bridge; attach the app containers so HTTPS stops 502.
2026-09-20 00:37:04 +02:00
michele ddab6917a3 Keep Caddy on pinscope_periscope after compose rename.
Pin the app bridge to the pre-rename network name and add DNS aliases
pinscope / periscope-frontend so the host proxy can reach the stack again.
2026-09-20 00:35:12 +02:00
michele 6b0e44a50c Pin VPS deploy to /root/periscope only.
Refuse update-periscope.sh unless dirname resolves to the canonical
checkout, set compose project name periscope, and document that the
GitHub clone URL may still be manvalan/pinscope.
2026-09-20 00:15:34 +02:00
michele 16c606ae3d Add MODE=pcb layout exam job with AI and deterministic checks.
Parallel pcb_status pipeline: parse board, classify domains/groups,
inventory traces, PE-LAY/PLC/SI/DRT checks, per-IC datasheet review.
Findings merge into the report UI. No auto-place or pcbnew write-back.
2026-09-19 22:54:17 +02:00
michele a2011dad91 Update PCB review plan: AI exam like schematic, no auto-place.
Adds per-IC LLM review, domains/groups as exam context, required
recommendations, and phased job MODE=pcb. Packing stays parked.
2026-09-19 22:43:58 +02:00
michele 721ede4243 Add PCB review plan: verify placement and routing, no auto-place.
Documents a parallel MODE=pcb exam job (inventory + datasheet-gated
checks) that reuses placement_check, si_check, and the placement job
pattern. Parks F2 packing/export.
2026-09-19 21:41:27 +02:00
748 changed files with 105016 additions and 2033 deletions
+209
View File
@@ -0,0 +1,209 @@
---
alwaysApply: true
---
## PURPOSE
This document defines the mandatory engineering rules for the Periscope project.
These rules are not suggestions.
They define:
* repository structure;
* coding standards;
* architectural principles;
* semantic modeling rules;
* Python/Rust language policy;
* testing requirements;
* verification requirements;
* Git workflow;
* commit/push/deployment policy;
* development-phase discipline.
Cursor must treat these rules as **mandatory project constraints**.
If an implementation conflicts with these rules, the implementation must be changed.
Do not silently relax, bypass, reinterpret, or ignore these rules.
---
# 1. CREATE THE PROJECT RULE STRUCTURE
Create and maintain the following structure:
```text
.cursor/
└── rules/
├── 00-coding-constitution.mdc
├── 10-architecture.mdc
├── 20-python.mdc
├── 30-rust.mdc
├── 40-testing.mdc
├── 50-verification.mdc
└── 60-git-workflow.mdc
docs/
└── development/
└── CODING_CONSTITUTION.md
```
The Markdown document is the human-readable master document.
The `.mdc` files are the operational Cursor rules.
The rules must be version-controlled with the project.
Do not create contradictory rules in different files.
If a conflict exists, resolve the conflict explicitly before continuing development.
---
# 2. CORE PRINCIPLE
## CODE THAT FITS IN YOUR HEAD
This is the fundamental Periscope engineering principle.
> Code must be locally understandable by an engineer without requiring reconstruction of a large hidden abstraction system.
Prefer:
* small modules;
* small functions;
* one responsibility;
* explicit dependencies;
* explicit data flow;
* simple data structures;
* precise names;
* deterministic behavior;
* minimal public APIs;
* composition over inheritance.
Avoid:
* huge functions;
* god classes;
* deep inheritance;
* speculative abstractions;
* hidden state;
* magic behavior;
* global mutable state;
* unnecessary frameworks;
* premature optimization;
* unnecessary indirection.
A function around 4060 lines is a warning signal, not an absolute limit.
The actual rule is local comprehensibility.
A 20-line function can violate the rule if it contains too many responsibilities.
A longer function may be acceptable if its structure remains obvious and justified.
---
# 3. ONE RESPONSIBILITY
Every function and module must have one primary responsibility.
Prefer:
```text
parse
normalize
build model
analyze
produce finding
report
```
Avoid a single function that:
* parses input;
* modifies the model;
* performs analysis;
* accesses external services;
* formats output;
* writes files;
* handles errors;
* and generates reports.
Separate responsibilities.
---
# 4. EXPLICIT DATA FLOW
Periscope must have explicit data flow.
Prefer:
```text
SOURCE
PARSER
NORMALIZED MODEL
ANALYZER
FINDING
REPORT
```
Avoid hidden communication through:
* global variables;
* singleton state;
* implicit registries;
* hidden caches;
* ambient configuration;
* side effects;
* undocumented environment state.
If a function needs important information, that information must be visible in its inputs or clearly owned state.
---
# 5. NO SPECULATIVE ABSTRACTION
Do not introduce an abstraction merely because it might become useful later.
Do not create unnecessary:
* factories;
* generic managers;
* service layers;
* repository layers;
* plugin systems;
* inheritance hierarchies;
* generic object wrappers;
* framework-like internal infrastructure.
Implement the actual requirement first.
Abstract only when there is a concrete and demonstrated reason.
---
# 6. COMPOSITION OVER INHERITANCE
Prefer composition.
Avoid deep class hierarchies.
Inheritance must have a clear semantic reason.
Do not use inheritance merely to share a few methods.
---
+406
View File
@@ -0,0 +1,406 @@
---
alwaysApply: true
---
# 7. DETERMINISTIC CORE
The verification core must be deterministic.
For the same:
```text
input
+
configuration
+
source data
```
Periscope must produce the same:
```text
model
calculations
findings
```
Do not make deterministic verification dependent on:
* LLM output;
* prompts;
* randomness;
* execution order;
* hidden state;
* uncontrolled external state.
---
# 8. LLM ROLE
LLMs may be used for:
* extraction;
* classification;
* datasheet interpretation;
* explanation;
* hypothesis generation;
* assistance.
LLMs must not be the authoritative deterministic verification engine.
The intended architecture is:
```text
SOURCE
STRUCTURED REQUIREMENT
DETERMINISTIC ANALYZER
FINDING
OPTIONAL LLM EXPLANATION
```
Not:
```text
SOURCE
LLM
probably wrong
```
---
# 9. EVIDENCE BEFORE CONCLUSION
Every engineering conclusion must be traceable to evidence.
Where applicable, preserve:
```text
observed fact
requirement
source
calculation
assumption
conclusion
confidence
severity
```
Do not silently transform assumptions into facts.
---
# 10. REQUIREMENT STRENGTH
Requirements must preserve their strength.
Use:
```text
MANDATORY
RECOMMENDED
TYPICAL
EXAMPLE
ENGINEERING_INFERENCE
```
Do not convert:
```text
RECOMMENDED
```
into:
```text
MANDATORY
```
Do not convert an example into an absolute rule.
Do not convert an engineering inference into documented manufacturer information.
---
# 11. SEVERITY AND CONFIDENCE ARE INDEPENDENT
A finding must be able to represent independent:
```text
severity
confidence
```
Examples that are valid:
```text
ERROR + LOW confidence
RISK + HIGH confidence
```
Do not use confidence as a substitute for severity.
---
# 12. INSUFFICIENT EVIDENCE
If the available information is insufficient to establish a conclusion:
```text
INSUFFICIENT_EVIDENCE
```
must be used.
Never invent missing engineering information.
Never invent:
* electrical limits;
* timing values;
* pin functions;
* voltages;
* currents;
* tolerances;
* PCB rules;
* thermal limits;
* datasheet requirements.
Missing evidence is not permission to guess.
---
# 13. SEMANTIC MODEL FIRST
Periscope must preserve domain semantics.
At minimum, distinguish concepts such as:
```text
Project
Component
Pin
Footprint
Pad
Net
Via
Track
Zone
PowerRail
SignalGroup
TimingEvent
Requirement
Constraint
DesignIntent
Evidence
Finding
```
Do not collapse semantically different physical objects into one generic object merely because they share coordinates, nets, or attributes.
---
# 14. SEMANTIC IDENTITY MUST SURVIVE TRANSFORMATIONS
A transformation must preserve the semantic identity of objects.
For example:
```text
PCB Via
```
must never become:
```text
Component Pad
```
merely because:
* it is close to a footprint;
* it is inside a footprint area;
* it is connected to GND;
* it shares a net;
* it has coordinates similar to a pad.
Similarly:
```text
Pad ≠ Via
Track ≠ Via
Zone ≠ Pad
Component Pin ≠ PCB Via
```
This is a fundamental Periscope rule.
---
# 15. ROOT CAUSE OVER SYMPTOM
When a false positive or incorrect result is discovered:
Do not simply suppress the finding.
Determine where the representation first becomes incorrect.
Example:
```text
PCB
parser
incorrect model
correct analyzer operating on incorrect model
incorrect finding
```
The fix belongs in the model/parser boundary, not necessarily in the analyzer.
Always investigate the complete chain:
```text
source
→ parser
→ normalized representation
→ semantic model
→ analyzer
→ finding
→ report
```
---
# 16. NO COMPONENT-SPECIFIC HACKS
Do not fix architecture problems with:
```text
if component == U1
```
or:
```text
if footprint == X
```
or:
```text
if net == GND
```
or hard-coded corrections such as:
```text
subtract N
ignore N
force expected count
```
unless the condition represents a genuine documented engineering rule.
A bug in generic PCB semantics must receive a generic semantic fix.
---
# 17. PHYSICAL SEMANTICS
Periscope is an electronic design verification system.
Its internal model must reflect physical reality.
Geometric proximity does not establish semantic identity.
For example:
```text
Via located inside footprint
```
does not imply:
```text
Via belongs to component as a pad
```
unless the PCB data model explicitly establishes that relationship.
Do not infer component relationships solely from proximity when stronger source information exists.
---
# 18. UNITS MUST BE EXPLICIT
Use explicit units.
Prefer:
```text
width_mm
delay_ns
frequency_hz
voltage_v
current_a
temperature_c
```
over ambiguous variables such as:
```text
width
delay
value
limit
```
when unit ambiguity is possible.
Never rely on undocumented implicit units.
---
# 19. NAMED CONSTANTS
Avoid magic numbers.
Prefer:
```text
MIN_SUPPLY_V
MAX_TRACE_LENGTH_MM
DEFAULT_SPI_CLOCK_HZ
```
over unexplained numeric literals.
Engineering constants must have traceable sources where appropriate.
---
# 20. ERROR CATEGORIES
Distinguish:
```text
tool failure
data failure
analysis result
insufficient evidence
engineering violation
```
Do not collapse fundamentally different failure modes into one generic error.
---
+28
View File
@@ -0,0 +1,28 @@
---
alwaysApply: true
---
# 32. PYTHON IS THE DEFAULT LANGUAGE
Python is the default implementation language for Periscope.
Use Python for:
* orchestration;
* datasheet processing;
* document parsing;
* LLM integration;
* requirement extraction;
* evidence management;
* project management;
* CLI;
* API integration;
* reporting;
* test orchestration;
* external tool integration;
* high-level analysis.
Do not rewrite Python into Rust merely because Rust exists in the project.
---
+94
View File
@@ -0,0 +1,94 @@
---
alwaysApply: true
---
# 33. RUST IS NOT A DEFAULT
Rust must not be introduced simply because code is new.
Rust is justified only when there is a demonstrated engineering requirement.
Valid reasons include:
* measured performance bottleneck;
* computationally intensive geometry;
* large-scale spatial processing;
* numerical computation;
* graph processing;
* memory pressure;
* deterministic high-performance computation.
Do not use Rust speculatively.
---
# 34. MEASURE BEFORE MOVING TO RUST
Required sequence:
```text
correct implementation
measurement
profiling
identified bottleneck
Rust implementation
benchmark
accept/reject based on evidence
```
Do not introduce Rust based on assumptions about performance.
---
# 35. RUST BOUNDARIES MUST BE COARSE-GRAINED
Prefer:
```text
Python
structured input
Rust engine
structured result
Python
```
Avoid excessive Python ↔ Rust calls for individual operations.
Rust should encapsulate meaningful computational workloads.
---
# 36. DO NOT PREMATURELY FREEZE THE CORE IN RUST
The semantic model should first become correct and well understood.
Prefer:
```text
semantic model
correctness
tests
architecture stabilization
profiling
Rust where justified
```
Do not rewrite the entire Periscope core in Rust simply to establish a Rust architecture.
---
+147
View File
@@ -0,0 +1,147 @@
---
alwaysApply: true
---
# 21. TESTING IS MANDATORY
Every meaningful implementation change requires tests.
At minimum test:
```text
normal case
failure case
boundary case
insufficient evidence
```
For semantic models, also test the boundaries between object types.
For PCB analysis, explicitly test:
```text
Pad
Via
Track
Zone
```
as distinct semantic entities.
---
# 22. TESTS MUST BE STRICT AND ABSOLUTE
Periscope tests are not advisory.
A test must define the exact expected behavior.
Do not use vague assertions such as:
```text
result is reasonable
result is not empty
analysis completed
```
when an exact result can be established.
Prefer assertions such as:
```text
expected object type == Via
expected pad count == 24
expected finding count == 0
expected finding code == X
expected severity == ERROR
expected confidence == HIGH
```
Where deterministic exact values are available, test them exactly.
Do not weaken tests merely to make an implementation pass.
Do not modify expected results to accommodate incorrect implementation behavior.
---
# 23. REGRESSION TEST FOR EVERY BUG
Every fixed bug must become a regression test.
Required sequence:
```text
BUG
REPRODUCE
TEST FAILS
FIX
TEST PASSES
FULL REGRESSION
```
A bug fix is not complete until the original failure is permanently represented by a test.
---
# 24. TEST THE NEGATIVE CASE
Do not test only:
```text
valid → pass
```
Also test:
```text
invalid → fail
```
and ensure that genuine errors remain detectable.
For example, if fixing:
```text
24 datasheet pins
24 footprint pads
N vias
```
verify that:
```text
24 datasheet pins
23 footprint pads
```
still produces a real mismatch.
The fix must remove false positives without suppressing true positives.
---
# 26. NO WEAKENING TESTS TO CLOSE A PHASE
Do not:
* delete failing tests;
* weaken assertions;
* skip tests;
* mark tests expected-to-fail;
* suppress failures;
* change expected values without engineering justification;
simply to make a macro-phase pass.
If a test exposes a real implementation problem, fix the implementation.
If the requirement itself is wrong, change the requirement explicitly and document why.
---
+245
View File
@@ -0,0 +1,245 @@
---
alwaysApply: true
---
# 37. CORRECTNESS BEFORE PERFORMANCE
Priority order:
```text
1. Correctness
2. Semantic integrity
3. Determinism
4. Testability
5. Readability
6. Maintainability
7. Performance
8. Optimization
```
Performance optimization must not compromise the first six without explicit justification.
---
# 38. MINIMAL PUBLIC APIs
Public APIs must be as small as practical.
Do not expose internal implementation details unnecessarily.
Prefer explicit interfaces.
Avoid API surface growth without a real requirement.
---
# 39. NO DEAD CODE
Remove or explicitly document:
* obsolete code;
* commented-out implementations;
* unused imports;
* unused abstractions;
* obsolete APIs;
* temporary workarounds.
Temporary adapters must be clearly identified and have a removal path.
---
# 40. COMMENTS
Comments should explain:
```text
WHY
```
rather than simply:
```text
WHAT
```
Do not comment obvious code.
Do document:
* non-obvious engineering decisions;
* semantic constraints;
* source-specific behavior;
* intentional limitations;
* reasons for unusual algorithms;
* compatibility constraints.
---
# 41. CHANGE MINIMIZATION
For bug fixes:
1. reproduce the problem;
2. locate root cause;
3. change the smallest appropriate architectural layer;
4. add regression test;
5. run relevant tests;
6. run full regression;
7. review the resulting design.
Do not combine unrelated refactoring with a bug fix unless necessary.
---
# 42. NO SPECULATIVE ENGINEERING
Do not invent engineering rules.
Every rule should be based on one of:
```text
documented requirement
datasheet/source evidence
standard
explicit design intent
validated engineering inference
```
If evidence is insufficient:
```text
INSUFFICIENT_EVIDENCE
```
---
# 43. DESIGN INTENT IS FIRST-CLASS
Do not assume that every unusual design decision is an error.
Periscope must be able to represent:
```text
INTENTIONAL_DESIGN
```
when the evidence supports that interpretation.
The system must distinguish:
```text
actual violation
intentional design
engineering observation
insufficient evidence
```
---
# 44. FINDING CATEGORIES
Findings may include:
```text
ERROR
RISK
REFERENCE_DEVIATION
ENGINEERING_OBSERVATION
INTENTIONAL_DESIGN
INSUFFICIENT_EVIDENCE
```
Do not collapse all deviations into ERROR.
Severity and confidence remain independent.
---
# 45. REVIEW QUESTIONS BEFORE COMPLETING ANY CHANGE
Before declaring a change complete, Cursor must verify:
```text
Is the implementation correct?
Is the root cause fixed?
Is the semantic model correct?
Is the data flow explicit?
Can the code fit in my head?
Is any abstraction unnecessary?
Is there hidden state?
Are units explicit?
Are engineering constants named?
Are assumptions distinguished from facts?
Are tests strict?
Are negative cases tested?
Are boundary cases tested?
Is insufficient evidence tested?
Could this change create a false positive?
Could this change suppress a true positive?
Is the full regression passing?
Is documentation updated?
Is the macro-phase actually complete?
```
---
# 46. FINAL ENGINEERING PRINCIPLE
Periscope must not become a clever software system.
It must become a:
```text
CORRECT
DETERMINISTIC
SEMANTICALLY ACCURATE
TESTABLE
TRACEABLE
READABLE
MAINTAINABLE
ENGINEERING SYSTEM
```
The preferred implementation is the simplest one that satisfies those properties.
When two implementations are technically correct, prefer the one with:
* fewer abstractions;
* fewer dependencies;
* less hidden state;
* clearer data flow;
* smaller modules;
* smaller APIs;
* easier testing;
* easier debugging;
* clearer semantics.
The governing principle is:
> **CODE THAT FITS IN YOUR HEAD.**
And the governing development discipline is:
> **NO PHASE IS COMPLETE UNTIL ITS TESTS PROVE IT.**
And the governing repository discipline is:
> **COMMIT AND PUSH AT THE PHASE BOUNDARY AFTER TESTS; DEPLOY ONLY AFTER A MACRO-PHASE.**
+121
View File
@@ -0,0 +1,121 @@
---
alwaysApply: true
---
# 25. PHASE GATES
Development is divided into macro-phases.
A macro-phase is not complete until:
1. implementation is complete;
2. all required tests exist;
3. all required tests pass;
4. full regression passes;
5. relevant integration tests pass;
6. static/type/lint checks pass where applicable;
7. no known blocker remains;
8. documentation is updated;
9. results have been reviewed;
10. the phase acceptance criteria are satisfied.
Only then is the macro-phase considered complete.
---
# 27. PHASE COMMIT AND PUSH POLICY
Do not commit after every small implementation step merely for convenience.
During a **phase**:
```text
implement
→ test
→ fix
→ test
```
The repository may contain intermediate working-tree changes.
At the **end of each phase**, after tests pass:
```text
PHASE TESTS
COMMIT
PUSH
```
Commit and push belong to the **phase** boundary, not to every edit.
Do not push broken or half-completed phase work merely to synchronize the repository.
---
# 28. MACRO-PHASE DEPLOY POLICY
**Deploy** happens only after a **macro-phase**, not after every phase.
A macro-phase may contain several phases (each already committed and pushed after its tests).
Never deploy an incomplete macro-phase.
Required sequence for a macro-phase:
```text
PHASES (each: implement → test → commit → push)
FULL REGRESSION
MACRO-PHASE ACCEPTANCE
DEPLOY
POST-DEPLOY VERIFICATION
```
If deployment verification fails, stop and investigate.
---
# 29. NO DEPLOY AT PHASE BOUNDARY
Commit + push after phase tests: **yes**.
Deploy after a phase that is not a completed macro-phase: **no**.
---
# 30. NO AUTOMATIC COMMIT/PUSH/DEPLOY DURING DEVELOPMENT
Cursor must not create commits, push, or deploy merely because a small task has finished.
Commit and push are **phase-boundary** operations (after tests).
Deploy is a **macro-phase-boundary** operation.
If explicitly instructed to deploy before a macro-phase is complete, Cursor must identify the conflict with this policy rather than silently proceeding.
---
# 31. GIT HISTORY IS ENGINEERING EVIDENCE
Do not rewrite Git history casually.
Do not:
* force-push;
* squash history;
* rewrite commits;
* detach repository history;
unless explicitly required by the project phase and explicitly authorized.
Git history may be relevant to provenance and licensing analysis.
Preserve it.
---
+7
View File
@@ -11,3 +11,10 @@ data/
.claude/plans/
.claude/memory/
simple_project/
periscope/dependency/frontend/public/faradworks-logo-white.png
periscope/dependency/frontend/public/power-tree.gif
periscope/dependency/frontend/public/file.svg
periscope/dependency/frontend/public/globe.svg
periscope/dependency/frontend/public/next.svg
periscope/dependency/frontend/public/vercel.svg
periscope/dependency/frontend/public/window.svg
+5 -5
View File
@@ -14,20 +14,20 @@ jobs:
with:
python-version: "3.12"
cache: pip
- run: pip install -r backend/requirements.txt pytest pytest-asyncio
- run: pip install -r periscope/src/backend/requirements.txt pytest pytest-asyncio
- run: pytest tests/ -q
frontend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
cache-dependency-path: periscope/src/frontend/package-lock.json
- run: chmod +x scripts/materialize-frontend.sh && scripts/materialize-frontend.sh
- run: npm ci
working-directory: .merge/frontend
- run: npm run build
working-directory: .merge/frontend
+7 -4
View File
@@ -49,10 +49,10 @@ skills-lock.json
data/
backend/data/
# Frontend
frontend/node_modules/
frontend/.next/
frontend/out/
.merge/
periscope/dependency/frontend/node_modules/
periscope/dependency/frontend/.next/
periscope/src/frontend/.next/
.next/
# retrospective
@@ -65,3 +65,6 @@ edif-files/
# Cloud agent scratch
agent-tools/
# Licensed protocol PDFs — keep on disk as the local archive; do not commit binaries
standards/protocol-specs/*.pdf
+4 -138
View File
@@ -1,149 +1,15 @@
# Periscope — Agentic Schematic Validation
Periscope validates hardware schematics against component datasheets. It extracts constraints from PDFs, parses netlists and BOMs into a queryable graph, and runs an agentic validation loop to flag design violations.
> **Open-core note.** This is the open-source core. A small set of files are
> "gateway-owned seams" — pass-through stubs here (`frontend/src/proxy.ts`,
> `use-optional-auth.ts`, `clerk-theme-provider.tsx`,
> `components/billing/*`, `sidebar-auth.tsx`, `pricing-section.tsx`,
> `analytics/*`, `lib/csp-hosts.ts`) that the hosted-cloud repo replaces
> with auth/billing implementations. Keep their export signatures stable,
> and never import auth/billing SDKs anywhere else in the frontend. On the
> backend, everything reaches billing only through
> `backend/services/billing_hook.py:get_billing()` (a no-op here).
## System Overview
Three layers:
| Layer | Location | Purpose |
|-------|----------|---------|
| **Core library** | `backend/periscopex/` | Models, parsers, graph builder, agentic validator, passive resolver, taxonomy, BOM summary, derating |
| **Backend** | `backend/` | FastAPI app — async pipeline orchestration, SSE progress, project/file storage |
| **Frontend** | `frontend/` | Next.js 16 app — project dashboard, pipeline progress, report viewer, derating, admin dashboard |
Plus `skills/` — extraction prompts (pintable, patterns, specs) inlined locally for DeepSeek. Do not upload to Anthropic Console.
The pipeline stages: Parse BOM → Extract IC Pintables → Extract Simple Components → Extract Passives → DigiKey Auto-Resolve + Value Fallback → Build Graph → Direct Datasheet Review. Pipeline runs can be cancelled mid-execution via `POST /api/pipeline/{id}/cancel`.
## Example Project
`simple_project/` is the reference design for development and testing:
- **MCU**: TI MSPM0G3507SPTR (U3) — 48-pin LQFP
- **USB-UART Bridge**: CH340E (U2)
- **LDO Regulator**: SPX3819M5-L-3-3 (U1) — 5V to 3.3V
- **ESD Protection**: USBLC6-2SC6 (D1)
- **Crystal**: 8 MHz (X1) with 18pF load caps (C9, C10)
Files: `.asc` (PADS-PCB netlist; `.edn` EDIF 2.0.0 also accepted), `.csv`/`.xlsx` (BOM), `design_graph.json` (committed reference fixture used by tests).
## Architecture Principles
- **Modular extractors** — Domain-specific extraction per component type, unified constraint schema
- **Netlist as graph** — Queryable bipartite graph (components + nets) with traversal helpers
- **LLM API for PDF extraction** — Forced tool calls for structured output (pintable, passive patterns, specs). Default provider is DeepSeek.
- **Prompt caching** — Anthropic stamps `cache_control`; Gemini uses CachedContent; DeepSeek uses automatic prefix cache (cache-hit tokens in usage).
- **Local extraction skills** — `skills/*/SKILL.md` is inlined and `validate.py` runs in-process. Never call `scripts/upload_skills.py` (Anthropic Console).
- **Direct datasheet review** — The model reads the IC datasheet plus circuit neighborhood, compares to the reference application circuit, and flags issues via graph query tools (`find_connected_components`, `get_net_for_pin`, `get_pintable`). DeepSeek converts PDFs to text (and page images on the vision model).
- **Datasheet page trimming** — Large PDFs are keyword-trimmed to relevant pages before sending to Claude, reducing token cost (`pypdf`)
- **DigiKey fallback (exact MPN only)** — When pattern-based and direct extraction fail, DigiKey API fetches product parameters for auto-resolve. DigiKey matches only on exact MPN; fuzzy hits are rejected to avoid polluting the shared library with wrong-dielectric / wrong-voltage parts.
- **Value-string fallback** — When DigiKey misses an R/C/L/FB passive, a value-string resolver maps the BOM `Value` string to typed passive specs. Value-derived specs are persisted per-project only — never to the shared library.
- **Per-IC review error isolation** — Direct datasheet review runs each IC independently; one malformed payload or bad response cannot kill the whole run. Failed ICs surface as skipped components with the error.
- **Cross-IC excerpt budget (per-neighbor)** — To verify an interface finding the reviewer can pull a *connected* IC's datasheet pages (`get_datasheet_excerpt`). The budget is a global per-review page ceiling **plus a per-neighbor sub-budget**, so verifying one interface is never starved by pages already spent on other neighbors.
- **Finding normalization is downgrade-only** — A post-review per-IC normalize pass (`services/normalize_findings.py`) drops self-cancelling findings, merges same-root-cause findings, and re-grades severity — but only ever *downward*. A deterministic clamp caps each finding at the reviewer's calibrated severity (and any `Unverified:` finding at WARNING, preserving the prefix).
- **Cross-IC finding dedup** — After all per-IC reviews complete, a single pass (`services/dedupe_findings.py`) collapses one physical interface defect reported from both endpoints into a single finding. Gated by `cross_ic_dedup_enabled`; fail-soft.
- **Capacitor voltage derating** — Deterministic derating table computed from graph (ceramic/tantalum/electrolytic percentages, pass/fail per capacitor)
- **Deterministic checks over heuristics** — Exact checks where possible
- **Zero coupling between layers** — Backend calls periscopex functions with paths; frontend talks to backend via REST + SSE
- **Library deduplication** — Shared library (`library/extracted/`, `library/patterns/`, `library/models/`, `library/passives/`, `library/datasheets/`) caches extractions across projects
- **Content-addressed datasheets** — `library/datasheets/blobs/{md5}.pdf` stores unique PDFs once; `library/datasheets/refs/{safe_mpn}.json` maps MPNs to blobs (dedupe + multi-MPN sharing)
- **Taxonomy-driven extraction** — Living component taxonomy (`taxonomy/`) with per-subtype classification and specs schemas
- **Per-stage model config** — Each pipeline stage can use a different Claude model (e.g., Sonnet for review, Haiku for auto-resolve)
- **API call logging** — Every Claude API call is logged with token counts, cost, and timing per pipeline run
- **Report versioning** — Each project run is stamped with the current app version on the first `/start` transition (`ProjectMeta.periscope_version`). The version comes from `frontend/content/changelog.md`'s latest `##` heading — single source of truth — read at backend startup via `backend/_version.py`.
## Datasheet Extraction
Extracted data lives in `library/extracted/` (shared) or per-project under the storage backend. One JSON per MPN, schema in `backend/periscopex/models.py`.
Per-MPN IC extraction captures:
1. **Pintable** — Pin number + name (required), description + alt functions (optional)
2. **Package info** — Base family, package, pin count, description
3. **Component subtype** — Dotted taxonomy path (e.g., `ic.mcu`, `ic.power.ldo`)
For discrete/simple components:
4. **Specs** — Component specs (value, tolerance, package, voltage rating, etc.); parameters are filtered against taxonomy specs schemas
Extraction inlines **local skills** (`skills/*/SKILL.md` + `validate.py`) against DeepSeek. Do not use Anthropic Console Skills.
## Claude Console Skills
```
skills/
├── extract-pintable/ # Pin table + package info + taxonomy
│ ├── SKILL.md # System prompt (YAML frontmatter + markdown)
│ ├── schema.json # Tool output schema
│ └── validate.py # Validation script
├── extract-pattern/ # Passive MPN pattern
└── extract-specs/ # Component specs (discrete, connectors, crystals, etc.)
```
## Taxonomy
Living component taxonomy in `taxonomy/` — one JSON file per top-level type (ic, passive, connector, crystal, discrete, fuse, switch, test_point, transformer). Each subtype entry includes `description` and `example_mpn`.
Key taxonomy features:
- **Ref prefix mapping** — `U→ic`, `R/C/L→passive`, `D/Q→discrete`, `X→crystal`, etc.
- **Dotted subtype paths** — e.g., `ic.mcu`, `passive.capacitor.ceramic`, `ic.protection.esd`
- **Dynamic growth** — `add_subtype()` adds new entries; concurrent-safe JSON writes
- **Specs schema auto-generation** — Type-level and subtype-level parameter specs schemas are auto-generated via Claude when a taxonomy entry has none; extraction discards parameters not in the schema (`extra_specs` field)
## Scripts
- `scripts/upload_skills.py` — leftover Claude Console uploader. **Do not run.** Skills are local + DeepSeek only.
- `scripts/migrate_datasheets_to_library.py` — One-time migration: copy per-project datasheets to `library/datasheets/` (dry-run by default, `--apply` to execute)
- `scripts/migrate_datasheets_to_blobs.py` — Migrate named-PDF datasheets into the content-addressed blobs/refs layout (dry-run by default, `--apply` to execute)
- `scripts/dedup_library_datasheets.py` — Remove redundant per-MPN datasheet PDFs when a passive pattern already has a `datasheet_key` (dry-run by default, `--apply` to execute)
- `scripts/gc_orphan_blobs.py` — Garbage-collect `library/datasheets/blobs/*.pdf` not referenced by any ref file
- `scripts/clear_rules_from_extractions.py` — Strip deprecated `rules`/`absolute_maximum_ratings` from existing library extractions
## Tech Stack
- **Core**: Python 3.12+, Pydantic 2.x, OpenAI SDK (DeepSeek), Anthropic SDK (optional), google-genai (optional), openpyxl, pypdf, PyMuPDF
- **Backend**: FastAPI, uvicorn, sse-starlette, pydantic-settings
- **Frontend**: Next.js 16 (App Router, Turbopack), React 19, Tailwind CSS v4, shadcn/ui (Base UI), react-pdf
- **AI**: DeepSeek Chat Completions (OpenAI-compatible) with forced tool calls for extraction and agentic review. Do not route stages to Anthropic.
- **Model**: `deepseek-flash` for extraction, review, auto-resolve, and normalize (per-stage overrides via `.env`)
- **Skills**: Local SKILL.md + validate.py on DeepSeek
- **External APIs**: DigiKey API v4 (OAuth2) — optional datasheet auto-fetch and parameter-based auto-resolve (`DIGIKEY_CLIENT_ID`, `DIGIKEY_CLIENT_SECRET`)
## Extracted Model Versioning
All `ComponentConstraints` extracted JSON files carry a `model_version` semver field:
- **Initial value** — set from `default_model_version` in `backend/skills_manifest.json` (starts at `1.0.0`)
- **Minor bump** — increment `default_model_version` in `skills_manifest.json` when extraction prompts change (do **not** run `upload_skills.py`).
**Rule**: When committing changes under `skills/`, bump `default_model_version` locally. Never call Anthropic.
## Development Guidelines
- Write tests against `simple_project/` — it's the ground truth
- Netlist parser and BOM parser are pure functions with no side effects
- All data structures use Pydantic models in `backend/periscopex/models.py`
- Frontend types in `frontend/src/lib/types.ts` must stay in sync with `backend/periscopex/models.py`
- Extraction prompts live in `skills/` (SKILL.md + schema.json + validate.py) and run locally against DeepSeek
- **Never swallow exceptions silently** — prefer logging or re-raising over bare `except: continue`. Silent failures hide real bugs.
Open-core checkout. **Native code** lives in `periscope/src`. **Inherited PinScope** lives in `periscope/dependency` (in-tree AGPL dependency — do not delete). Root `LICENSE` is AGPL-3.0.
## Running
```bash
# Backend (copy backend/.env.example to .env at repo root first)
# Backend (copy periscope/dependency/backend/.env.example to .env at repo root first)
python3 -m uvicorn backend.main:app --reload # localhost:8000
# Frontend
cd frontend && npm run dev # localhost:3000
cd periscope/dependency/frontend && npm run dev # localhost:3000
```
Local mode needs no cloud services and no auth — projects are stored in `data/` and you are `user_id="local"` with admin access.
See `periscope/README.md` and root `README.md`.
+66 -43
View File
@@ -1,83 +1,106 @@
# Periscope (DeepSeek)
# Periscope
Periscope reviews schematics the way a good senior engineer does: with the datasheets open.
Periscope is full **PCB analysis** for a board you intend to send to fab with confidence. Schematic review is a stage, not the deliverable.
This tree is adapted from [manvalan/pinscope](https://github.com/manvalan/pinscope) so the pipeline talks to the **DeepSeek API** (`deepseek-flash`, with legacy aliases still accepted). Do not use Anthropic.
Give it a netlist, a BOM, datasheet PDFs, and a KiCad PCB. It builds a queryable graph of the design, extracts manufacturer constraints once into a shared library, then checks both the circuit and the copper: pads, tracks, vias, zones, measured geometry, and the interfaces that are actually on **this** board.
Give it a netlist, a BOM, and your datasheet PDFs. It builds a graph of your design, reads each IC's datasheet, and checks the circuit around every part against what the manufacturer actually specifies — reference application, pin functions, absolute maximums, recommended operating conditions. Every finding points at the datasheet page that backs it up.
Live instance: [https://periscope.michelebigi.it](https://periscope.michelebigi.it)
## What changed for DeepSeek
This tree is the Periscope product (operator: Michele Bigi). It is derived from [Faradworks/Pinscope](https://github.com/Faradworks/Pinscope); Faradworks does not operate this instance.
DeepSeek's Chat Completions API is OpenAI-compatible but **does not accept native PDF documents**. Periscope therefore:
## What it checks — and what it will not invent
1. **Extracts datasheet text** with `pypdf` (page-marked) and sends it as chat content.
2. **Renders pages to JPEG** with PyMuPDF when the stage uses a vision model, so pin diagrams and tables survive.
3. **Runs extraction skills locally.** `skills/*/SKILL.md` is inlined as the system prompt; `validate.py` runs in-process. You do not need Anthropic Console Skills.
4. **Round-trips `reasoning_content`** when DeepSeek thinking mode is on, so multi-turn review and tool calls do not 400.
USB pair impedance, Ethernet class, and trace current versus width are **examples** of gated checks. They run when that bus, connector, or datasheet number exists on the board. They are not a catalog of every interface in electronics.
Default routing:
**Semantic objects stay distinct.** A via is not a pad. A track is not a via. A zone is not a pad. Sharing a net, sitting inside a courtyard, or having nearby coordinates does not change the object type.
| Stage | Model |
**Evidence before conclusion.** If the datasheet, netlist, BOM, or `.kicad_pcb` does not supply the number, Periscope records `INSUFFICIENT` (or skips the check). It does not invent current, impedance, copper weight, geometry, IEC creepage, or “typical USB 500 mA”.
**Trace current uses datasheet current only.** Width versus load (`PE-PWR`) runs when the datasheet reports `I_load` / `Imax` / `I_abs`. Missing that current is a skip — not a guessed ampacity table, not via-IPC folklore.
**Interface class certifiers are gated on parts that are present.** USB-C, RJ45/Ethernet, PoE, and DDR-style certifiers fire only if that connector or device is on the graph. No USB-C receptacle → no USB-C findings (silence, not N/A). A bare RJ45 is Ethernet, not PoE. No DDR device → no DDR findings.
Periscope does **not** claim FEM, thermal spreading, OpenEMS, or a field solver. Closed-form Z0 comes from vendored ImpedenceFinder (`vendor/impedancefinder/`; upstream license UNKNOWN).
Findings keep FACT, REQUIREMENT, and INFERENCE apart. Recommended datasheet notes are not errors. The same finding object is used for schematic (`MODE=run`) and PCB (`MODE=pcb`).
## Repository layout
| Path | Role |
| --- | --- |
| Pintable / pattern / specs extraction | `deepseek-flash` (native vision) |
| Per-IC datasheet review | `deepseek-flash` |
| Auto-resolve / normalize | `deepseek-flash` |
| `periscope/src/` | Native Periscope (finding engine, PCB/placement, DeepSeek, Dockerfiles, KiCad plugin) |
| `periscope/dependency/` | Inherited PinScope (in-tree AGPL dependency — do not delete) |
| `backend/__init__.py` | Merges the two `backend` packages for local imports |
| `scripts/` | `update-periscope.sh`, `materialize-frontend.sh`, smoke wrapper |
| `vendor/impedancefinder/` | Third-party Z0 core (not FEM) |
| `LICENSE` | GNU AGPL v3 |
Override with `PROVIDER_*` and `MODEL_*_DEEPSEEK` in `backend/.env`. See `backend/.env.example`.
See `periscope/README.md` for the physical split.
## How it works
## Run locally
<p align="center">
<img src="docs/how-it-works.svg" width="920" alt="Pipeline: the netlist and BOM are parsed into a design graph; datasheet PDFs are extracted into pin tables and specs; a per-IC review reads both and files findings cited to datasheet pages; the derating table and BOM roll-up are computed straight from the graph, no model involved.">
</p>
1. **Parse** the BOM (CSV/XLSX) and netlist (PADS-PCB `.asc` or EDIF 2.0.0 `.edn`) into a queryable bipartite graph of components and nets.
2. **Extract** pin tables and specs from the PDFs. Large datasheets are trimmed to the relevant pages first, and every extraction is cached in a shared library.
3. **Review** each IC in isolation. The model gets the datasheet plus that IC's circuit neighborhood, can query the graph, and files findings with severity, reasoning, and page citations. Extraction now also stores absolute-maximum ratings so the reviewer does not have to rediscover supply limits from a 300-page PDF.
4. **Compute** the deterministic parts deterministically — BOM roll-up and a capacitor voltage-derating table come straight from the graph.
## Try it on the bundled design
`simple_project/` is a small MSPM0G3507 board with a CH340E USB-UART bridge and an SPX3819 LDO.
You need Python 3.12+, Node 20+, and a [DeepSeek API key](https://platform.deepseek.com/):
Python 3.12+, Node 20+, and a [DeepSeek API key](https://platform.deepseek.com/) for live extraction and review. Offline graph/smoke does not need the key.
```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r backend/requirements.txt
cp backend/.env.example backend/.env # set DEEPSEEK_API_KEY
pip install -r periscope/src/backend/requirements.txt
cp periscope/src/backend/.env.example .env # set DEEPSEEK_API_KEY
python3 -m uvicorn backend.main:app --reload --host 127.0.0.1 --port 18741
```
# in another terminal
cd frontend && npm install
Frontend — overlay native UI onto the inherited shell, then start Next.js (this is what CI runs):
```bash
./scripts/materialize-frontend.sh
cd .merge/frontend && npm install
NEXT_PUBLIC_API_URL=http://127.0.0.1:18741 npm run dev -- --port 18742 --hostname 127.0.0.1
```
Open the frontend URL, create a project, and feed it the netlist and BOM from `simple_project/`. Datasheets are fetched automatically (LCSC, TI, optional DigiKey); you can still drop in PDFs by hand. Fetched PDFs and extracted pin tables land in the **Library** (sidebar) and are reused on later projects. Everything runs locally against your own DeepSeek key; projects and the extraction library live in `data/`. Skills are local `skills/*/SKILL.md` — do not run `scripts/upload_skills.py`.
Open the frontend URL, create a project, and upload a netlist plus BOM. A `.kicad_pcb` is required for the PCB job; without it the project can complete schematic review only. `periscope/dependency/simple_project/` is a small bundled schematic fixture (MSPM0G3507 + CH340E + SPX3819).
Projects and the extraction library live in `data/` (gitignored). Extraction skills are local `periscope/src/skills/*/SKILL.md`. Do not run an Anthropic Console uploader.
Tests from the repo root:
```bash
pip install pytest pytest-asyncio
pytest tests/ -q
python3 scripts/smoke_simple_project.py # offline
```
## Docker
```bash
cp backend/.env.example .env # set DEEPSEEK_API_KEY
cp periscope/src/backend/.env.example .env # set DEEPSEEK_API_KEY
docker compose up --build
```
Backend on port 8080, frontend on port 3000.
Backend listens on port 8080, frontend on port 3000 (`docker-compose.yml`).
### Update a live instance (e.g. periscope.michelebigi.it)
### Live host
On the server, from the Periscope checkout:
The public site is rebuilt from **`/root/periscope`** with the script that actually ships:
```bash
cd /root/periscope
./scripts/update-periscope.sh
```
The script pulls the current branch, writes `NEXT_PUBLIC_API_URL` / `CORS_ORIGINS` for `https://periscope.michelebigi.it`, rebuilds both Docker images, and leaves `data/` alone. First run: put `DEEPSEEK_API_KEY` in `.env` at the repo root (compose reads that file). `--no-pull` skips git. `SITE=https://other.host ./scripts/update-periscope.sh` overrides the public URL.
`--no-pull` skips git. `SITE=https://other.host ./scripts/update-periscope.sh` overrides the public URL. The script refuses to run unless the checkout is `/root/periscope` (override with `CANONICAL_ROOT` only if the host layout differs). It does not touch `data/`.
Do not set `ENVIRONMENT=production` unless Clerk auth is configured — that flag refuses to boot with auth disabled.
## Source
| Remote | URL |
| --- | --- |
| GitHub | [https://github.com/manvalan/pinscope](https://github.com/manvalan/pinscope) (`git@github.com:manvalan/pinscope.git`) |
| Gitea | [http://192.168.1.71:3000/michele/periscope.git](http://192.168.1.71:3000/michele/periscope.git) |
Push both: `git push github && git push gitea` (no force).
## License
AGPL-3.0, same as upstream Pinscope (Faradworks). For commercial licensing of the original, write to dev@faradworks.com.
[AGPL-3.0](LICENSE) — GNU Affero General Public License v3.0.
This tree is derived from [Faradworks/Pinscope](https://github.com/Faradworks/Pinscope). For a commercial license of **upstream Pinscope**, contact Faradworks as they publish it. For this Periscope instance, contact Michele Bigi (mikbigi@gmail.com).
-33
View File
@@ -1,33 +0,0 @@
FROM python:3.12-slim
RUN apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Install dependencies first (layer caching).
# Open-core: the private gateway repo adds backend/requirements-gateway.txt
# (Stripe, etc.); a plain core checkout has no such file and skips that step.
COPY backend/requirements*.txt /app/backend/
RUN pip install --no-cache-dir -r /app/backend/requirements.txt \
&& if [ -f /app/backend/requirements-gateway.txt ]; then \
pip install --no-cache-dir -r /app/backend/requirements-gateway.txt; \
fi
# Copy application code
COPY backend/ /app/backend/
# Copy runtime assets needed by the backend
# Taxonomy: fallback for local mode; GCS mode downloads from bucket
COPY taxonomy/ /app/taxonomy/
# Extraction skills (SKILL.md + validate.py) — required for DeepSeek/Gemini
COPY skills/ /app/skills/
# Changelog: single source of truth for the user-facing Periscope version.
COPY frontend/content/changelog.md /app/changelog.md
# ImpedenceFinder closed-form engine (no OpenEMS / pcbnew).
COPY vendor/ /app/vendor/
EXPOSE 8080
CMD ["uvicorn", "backend.main:app", "--host", "0.0.0.0", "--port", "8080"]
+38
View File
@@ -0,0 +1,38 @@
"""Backend package facade: native Periscope + inherited PinScope.
``periscope/src/backend`` and ``periscope/dependency/backend`` are merged via
pkgutil path extension. Do not put application modules in this directory.
"""
from __future__ import annotations
import sys
from pathlib import Path
from pkgutil import extend_path
_REPO = Path(__file__).resolve().parents[1]
_SRC = _REPO / "periscope" / "src"
_DEP = _REPO / "periscope" / "dependency"
# Last insert is searched first: native src overlays inherited dependency.
for _p in (_DEP, _SRC):
_s = str(_p)
if not _p.is_dir():
continue
if _s in sys.path:
sys.path.remove(_s)
sys.path.insert(0, _s)
def _prefer_native_backend(paths: list[str]) -> list[str]:
src, other, dep = [], [], []
for p in paths:
norm = p.replace("\\", "/")
if "/periscope/src/" in norm:
src.append(p)
elif "/periscope/dependency/" in norm:
dep.append(p)
else:
other.append(p)
return src + other + dep
__path__ = _prefer_native_backend(list(extend_path(__path__, __name__)))
-93
View File
@@ -1,93 +0,0 @@
"""Validate datasheet layout_rules. Distances stay null unless numeric."""
from __future__ import annotations
from typing import Any
from packaging.version import Version
KNOWN_KINDS = frozenset({"decoupling_proximity", "thermal_via", "keepout", "length_match"})
def _num(v: Any) -> float | None:
if v is None or v is False:
return None
if isinstance(v, bool):
return None
if isinstance(v, (int, float)):
return float(v)
try:
return float(str(v).strip())
except (TypeError, ValueError):
return None
def has_any_layout_rule(raw: object) -> bool:
"""True when extraction already produced at least one structured rule."""
if not isinstance(raw, list):
return False
for row in raw:
if isinstance(row, dict) and str(row.get("kind") or "").strip() in KNOWN_KINDS:
return True
return False
def needs_layout_rules_refresh(
data: dict,
*,
min_scan_version: str,
) -> bool:
"""True when layout_rules are empty and the extract predates the scan version.
After a successful extract at ``min_scan_version`` or newer, an empty
``layout_rules`` list means the datasheet had no guidance — do not loop.
"""
if has_any_layout_rule(data.get("layout_rules")):
return False
ver = str(data.get("model_version") or "0.0.0")
if not min_scan_version or min_scan_version == "0.0.0":
return False
try:
return Version(ver) < Version(min_scan_version)
except Exception:
return True
def validate_layout_rules(raw: list | None) -> tuple[list[dict], list[str]]:
"""Return (normalized rows, errors). Empty list is a valid skip."""
if not raw:
return [], []
if not isinstance(raw, list):
return [], ["layout_rules must be an array"]
ok: list[dict] = []
errors: list[str] = []
for i, row in enumerate(raw):
if not isinstance(row, dict):
errors.append(f"layout_rules[{i}] must be an object")
continue
kind = str(row.get("kind") or "").strip()
if kind not in KNOWN_KINDS:
errors.append(f"layout_rules[{i}] unknown kind {kind!r}")
continue
dist = _num(row.get("max_distance_mm"))
via = row.get("min_via_count")
via_i = None
if isinstance(via, int) and not isinstance(via, bool):
via_i = via
elif via is not None:
n = _num(via)
via_i = int(n) if n is not None else None
page = row.get("source_page")
page_i = int(page) if isinstance(page, int) else None
ok.append({
"kind": kind,
"pin": row.get("pin"),
"cap_value_hint": row.get("cap_value_hint"),
"max_distance_mm": dist,
"same_layer": row.get("same_layer") if isinstance(row.get("same_layer"), bool) else None,
"min_via_count": via_i,
"net_class": row.get("net_class"),
"note": row.get("note"),
"source_page": page_i,
})
return ok, errors
-91
View File
@@ -1,91 +0,0 @@
"""G1 SI: intra-pair skew only when the datasheet gives millimetres.
Pair names (_DP/_DM, _P/_N) only identify which nets to compare. The
limit is never 3W, USB spec folklore, or a default millimetre.
"""
from __future__ import annotations
import math
from backend.periscopex.models import DesignGraph, Finding, LayoutGraph, LayoutSegment
from backend.periscopex.validate import _match_constraints
_PAIR_SUFFIXES = (("_DP", "_DM"), ("_P", "_N"), ("+", "-"))
def _seg_len(seg: LayoutSegment) -> float:
return math.hypot(seg.end[0] - seg.start[0], seg.end[1] - seg.start[1])
def net_length_mm(layout: LayoutGraph, net: str) -> float:
return sum(_seg_len(s) for s in layout.segments if s.net == net)
def partner_net(name: str) -> str | None:
for a, b in _PAIR_SUFFIXES:
if name.endswith(a):
return name[: -len(a)] + b
if name.endswith(b):
return name[: -len(b)] + a
return None
def _length_match_limit_mm(constraints_map: dict, graph: DesignGraph) -> tuple[float, int | None] | None:
for comp in graph.components.values():
cons = _match_constraints(comp.mpn, constraints_map)
if not cons:
continue
for rule in cons.layout_rules or []:
if rule.get("kind") != "length_match":
continue
mm = rule.get("max_distance_mm")
if mm is None:
continue
return float(mm), rule.get("source_page")
return None
def check_si(
graph: DesignGraph,
constraints_map: dict,
layout: LayoutGraph | None,
) -> list[Finding]:
if layout is None or not layout.segments:
return []
limit = _length_match_limit_mm(constraints_map, graph)
if limit is None:
return []
max_mm, page = limit
seen: set[tuple[str, str]] = set()
findings: list[Finding] = []
names = {s.net for s in layout.segments if s.net}
for net in names:
partner = partner_net(net)
if not partner or partner not in names:
continue
key = tuple(sorted((net, partner)))
if key in seen:
continue
seen.add(key)
skew = abs(net_length_mm(layout, net) - net_length_mm(layout, partner))
if skew <= max_mm:
continue
findings.append(Finding(
designator="layout",
mpn="",
aspect="si",
finding=(
f"Intra-pair skew {skew:.1f} mm on {key[0]}/{key[1]} "
f"(datasheet max {max_mm:g} mm)."
),
why=f"length_match max_distance_mm={max_mm:g}.",
status="ERROR",
recommendation="Length-match the differential pair.",
source="si_check",
rule_id="PE-SI-001",
net=net,
pins=[],
source_page=page,
))
return findings
+20 -7
View File
@@ -1,9 +1,16 @@
# Canonical compose project on the VPS is "periscope" (not the GitHub
# clone folder name "pinscope"). Bind mounts stay relative to the checkout.
# Host Caddy (railway-caddy) lives on Docker network pinscope_pinscope and
# reverse_proxies periscope-frontend:3000 / periscope-backend:8080. The
# update script connects these containers to that network after up.
name: periscope
services:
backend:
build:
context: .
dockerfile: backend/Dockerfile
dockerfile: periscope/src/backend/Dockerfile
container_name: periscope-backend
restart: unless-stopped
@@ -18,18 +25,21 @@ services:
volumes:
- ./data:/app/data
- ./taxonomy:/app/taxonomy
- ./periscope/src/taxonomy:/app/taxonomy
ports:
- "8080:8080"
networks:
- periscope
periscope:
aliases:
- periscope-backend
- pinscope-backend
frontend:
build:
context: ./frontend
dockerfile: dockerfile
context: .
dockerfile: periscope/src/frontend/dockerfile
args:
NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL:-http://localhost:8080}
NEXT_PUBLIC_AUTH_MODE: ${NEXT_PUBLIC_AUTH_MODE:-}
@@ -44,8 +54,11 @@ services:
- "3000:3000"
networks:
- periscope
periscope:
aliases:
- periscope-frontend
- pinscope
- pinscope-frontend
networks:
periscope:
+669
View File
@@ -0,0 +1,669 @@
# Albero delle analisi Periscope
Versione codice **2.63.1** (`periscope/src/frontend/content/changelog.md`). Letto in `/Users/michelebigi/Development/periscope`. Costituzione senza eccezioni: via ≠ pad ≠ traccia ≠ zona; niente I/Z/mm inventati; skip se manca evidenza. **Non è DRC KiCad.** DRC = KiCad. Questo documento mappa lanalisi, non implementa.
I test pytest stanno in `tests/datasheet/`, `tests/library/`, `tests/schematic/`, `tests/pcb/`, `tests/af_ai/` (stessi file di 2.62.1, cartelle di mestiere). I path `tests/test_*.py` sotto i nodi restano i nomi file.
Due pipeline più una porta libreria (non è un esame):
0. **Libreria**`POST /api/library/datasheets` registra un componente da PDF senza `MODE=run`/`MODE=pcb`.
1. **Schematico / review AI**`MODE=run`, `services/pipeline.py``validate_design_async` (`validation.py`): estrazione datasheet, check deterministici, review IC DeepSeek.
2. **Esame PCB**`MODE=pcb`, `services/pcb_pipeline.py``run_pcb_checks` (`pcb_checks.py`, lista 2.62.1 **invariata**) + sezione additiva AF Board+AI (`af_ai_hf.py`) + review AI PCB (`pcb_review.py` / `pcb_validation.py`). Non auto-place.
I certifier USB-C / Ethernet / PoE girano su **entrambe** le pipeline (grafo, non geometria). DDR / CPU / FPGA / USB-PD sono la stessa qualità di finding ma partono da `run_pcb_checks` (grafo). Niente pezzo sul grafo → silenzio, non N/A.
Nodi analisi: **108** (99 PE-* + 1 LED senza `rule_id` + 8 processo estrazione/AI). Test pytest citati sotto i nodi: nomi reali da `tests/`.
---
```
Periscope 2.63.1
├── 0. Libreria (porta, non esame)
│ └── PDF + MPN → scheda (inbox IC / passivo / discreto) senza MODE=run/pcb
├── 1. Schematico / review AI (MODE=run)
│ ├── ingest (non è analisi: parser → grafo)
│ ├── estrazione datasheet
│ ├── check deterministici schema
│ ├── certifier di classe (condivisi con PCB)
│ └── review AI per-IC + post-pass
└── 2. Esame PCB (MODE=pcb)
├── ingest layout (non è DRC)
├── run_pcb_checks ← 2.62.1 invariato (SI + HF line inclusi)
│ ├── net / footprint
│ ├── placement vs layout_rules
│ ├── SI + linee HF (2.62.0 Fase A)
│ ├── DDR / CPU / FPGA (2.62.0)
│ ├── potenza / via / termico
│ ├── derating / timing / PI
│ ├── ESD / return / EMI / SPOF
│ ├── BOM ↔ PCB ↔ datasheet
│ └── resto Fase B (2.62.1)
├── AF Board + AI (additivo: flag → investigate_hf_hypotheses; non sostituisce SI/HF)
├── review AI PCB
└── tab antenna RF (non in run_pcb_checks)
```
---
## 1. Schematico / review AI (`MODE=run`)
Orchestrazione: `pipeline.py` stadi `bom_parse``ic_extraction``simple_extraction``passive_extraction``graph_build``validation`. Check deterministici: `_run_deterministic_checks` in `validation.py`. Finding ID schema `PS-{ref}-{nnn}` (non `PCB-`).
### 1.1 Ingest (prerequisito, non analisi)
Parser e grafo non emettono PE-*. Skip MPN: `ic_mpn_skip_reason` (silenzio onesto, niente MPN inventato).
- Test parser/grafo: `tests/test_bom_parser.py` (`test_parse_bom_uses_value_for_ic_when_mpn_column_empty`, `test_parse_bom_keeps_pnm_and_datasheet_url`); `tests/test_hubaudio_bom.py` (tutti e 4); `tests/test_netlist_parser.py` (tutti e 3); `tests/test_edif_parser.py` (14); `tests/test_kicad_parser.py` (17); `tests/test_kicad_project.py` (19); `tests/test_netlist_bundle.py` (9); `tests/test_functional_groups.py` (8).
- Test overlay parser: `tests/test_periscope_parsers_rewrite.py`, `tests/test_periscope_graph_rewrite.py`, `tests/test_periscope_models_rewrite.py`.
### 1.2 Estrazione datasheet (processo)
Skip se manca PDF o lo skill non ha numero. Libreria `library/extracted` condivisa schema+PCB. PCB review non rilegge il PDF (`pdf_path=None`).
#### `extract-pintable` — skill `skills/extract-pintable/`
Modulo: `services/datasheet_extract.py` + `llm/local_skill.py`. Analizza: pin table, package, taxonomy IC.
- Skip se: niente PDF; IC già in libreria alla `model_version` minima.
- Test: `tests/test_native_datasheet_extract.py` (`test_coerce_abs_max_matches_inherited`, `test_native_extract_has_no_anthropic_import`); `tests/test_pdf_ingest.py` (6); `tests/test_deepseek_provider.py` (`test_local_skills_load`, `test_extract_pdf_text_includes_page_markers`, `test_wroom_rejects_bare_soc_pin1_ant`); `tests/test_periscope_taxonomy_skills_src.py` (`test_pintable_skill_mentions_save_tool_and_wroom`, `test_skills_dir_is_src_and_local`).
#### `extract-specs` — skill `skills/extract-specs/`
Analizza: specs discreti/connettori/cristalli; parametri fuori taxonomy → scartati.
- Skip se: niente PDF o tipo non in `SIMPLE_TYPES`.
- Test: `tests/test_pdf_ingest.py` (`test_coerce_abs_max_keeps_valid_drops_junk`); `tests/test_layout_rules.py` (5 — `layout_rules` numerici, niente mm inventati).
#### `extract-pattern` — skill `skills/extract-pattern/`
Analizza: pattern MPN passivi (R/C/L/FB).
- Skip se: MPN opaco; DigiKey/value fallback copre prima.
- Test: `tests/test_inductor_specs.py` (13, Z ferrite solo se il PDF dice N Ω @ freq); `tests/test_pcb_software_bugs.py` (`test_lqw_decoder_and_unknown_skip`, `test_fb1_blm_is_bead_not_dcr_resistor`).
#### Resolve DigiKey / catalogo (esatto MPN)
Modulo: `services/digikey.py`, `passive_from_distributor.py`, `passive_from_mpn.py`. Analizza: parametri catalogo per auto-resolve. Hit fuzzy rifiutati.
- Skip se: MPN non esatto; API assente (fail-soft).
- Test: `tests/test_digikey_match.py` (3); `tests/test_passive_from_distributor.py` (7); `tests/test_passive_from_mpn.py` (7); `tests/test_datasheet_finder.py` (17); `tests/test_library.py` (5).
#### Resolve da stringa Value (solo progetto)
Modulo: `services/passive_from_value.py`. Specs value-derived **non** in libreria condivisa.
- Skip se: stringa ambigua / placeholder.
- Test: `tests/test_passive_from_value.py` (8).
### 1.3 Check deterministici schema
Fail-soft per modulo. Senza evidenza: skip (lista vuota), non folklore.
#### `PE-MUX-001` — `pin_mux_check.py`
Analizza: funzione pin vs net (UART/SPI/I2C mux).
Skip se: `functions` vuote; link inter-device stesso peripheral; net opaco.
- Test: `tests/test_pin_mux_check.py``test_real_defect_uart5_swapped_is_error`, `test_correct_assignment_no_finding`, `test_inter_device_same_peripheral_link_is_skipped`, `test_transceiver_peer_without_peripheral_still_fires`, `test_empty_functions_skipped`, `test_pin_exposes_peripheral_but_not_signal_no_complement`, `test_opaque_net_not_flagged`, `test_token_parser_and_normalizer`, `test_spi_legacy_net_names_match_modern_pin_functions`, `test_spi_controller_peripheral_names_are_synonyms`, `test_simple_project_uart0_nets_are_feasible_on_mspm0_pins`, `test_simple_project_uart0_swapped_on_mspm0_is_error`, `test_spi_genuine_infeasibility_still_fires_with_modern_names`, `test_finding_prints_full_raw_capability_list_and_intent_caveat`, `test_legacy_report_without_source_validates`.
#### `PE-NC-001` — `nc_pin_check.py`
Analizza: pin NC collegato a net attivo.
Skip se: niente pintable.
- Test: `tests/test_nc_pin_check.py``test_nc_pin_on_active_net_warns`, `test_nc_pin_on_nc_net_silent`, `test_no_pintable_silent`.
#### `PE-DEC-001` / `PE-DEC-002` — `passive_rail_check.py` `check_supply_decoupling`
Analizza: condensatore sul net di alimentazione IC (001 presenza; 002 valore vs datasheet).
Skip se: net NC; pin enable strap; manca valore per 002.
- Test: `tests/test_passive_rail_check.py``test_missing_decoupling_is_warning`, `test_cap_to_gnd_clears_decoupling`, `test_enable_strapped_to_rail_is_not_decoupling`, `test_nc_supply_net_is_skipped`, `test_ldo_vout_needs_cout`, `test_ldo_vout_100n_only_is_value_warning`, `test_vdd_100n_is_not_a_value_warning`, `test_ki_cad_voltage_prefix_is_power`, `test_fb_and_rn_prefixes`.
#### `PE-I2C-001` / `PE-I2C-002` — `passive_rail_check.py` `check_i2c_pullups`
Analizza: pull-up I2C (001 presenza; 002 valore vs banda).
Skip se: pin SDA è alias SPI; pull-up senza valore (002 non sizato); bus assente.
- Test: `tests/test_passive_rail_check.py``test_i2c_missing_pullup`, `test_i2c_pullup_present`, `test_i2c_pullup_to_3v3_digital_typed_as_signal`, `test_spi_pin_alias_sda_is_not_i2c`, `test_i2c_from_slash_alias_in_pin_name`, `test_i2c_4k7_pullup_is_in_nxp_wide_band`, `test_i2c_100ohm_pullup_is_too_stiff`, `test_i2c_100k_pullup_is_too_weak`, `test_i2c_pullup_without_value_is_not_sized`.
#### `PE-RST-001` / `PE-RST-002` — `passive_rail_check.py` `check_reset_pullups`
Analizza: reset/enable pull (001 presenza; 002 verso vs datasheet).
Skip se: GPIO guida il reset.
- Test: `tests/test_passive_rail_check.py``test_reset_no_finding_when_gpio_drives`, `test_reset_floating_is_warning`, `test_nrst_pulldown_is_warning`, `test_nrst_pullup_is_not_pulldown`.
#### `PE-BOM-001` / `PE-BOM-002` — `bom_match_check.py`
Analizza: MPN schema vs BOM (001 mismatch; 002 riga BOM orfana).
Skip se: mappa schematica vuota (PADS/EDIF senza properties).
- Test: `tests/test_bom_match_check.py``test_matching_mpns_produce_no_findings`, `test_mpn_mismatch_is_error_ps_bom_001`, `test_orphan_bom_ref_is_warning`, `test_mpn_case_and_whitespace_are_not_a_mismatch`, `test_empty_bom_mpn_with_schematic_mpn_is_not_a_mismatch`, `test_empty_schematic_map_skips_check`, `test_legacy_design_graph_without_source_fields_still_validates`, `test_build_graph_kicad_mpn_mismatch_surfaces`.
#### `PE-DNP-001` — `dnp_check.py`
Analizza: DNP vs enable floating.
Skip se: colonna DNP assente.
- Test: `tests/test_dnp_check.py``test_dnp_pull_leaves_enable_floating`, `test_fitted_pull_is_silent`, `test_no_dnp_column_skips_floating_enable`, `test_parse_bom_reads_dnp_and_skips_when_column_absent`.
#### LED corrente — `led_current_check.py` (nessun `PE-*`)
Analizza: I_f Ohm vs rating canale. Source `led_current_check`.
Skip se: niente `forward_current_*`; tensione rail sconosciuta (non si indovina).
- Test: `tests/test_led_current_check.py``test_over_current_is_error`, `test_proper_resistor_no_finding`, `test_unknown_rail_no_error`, `test_no_rating_skipped`, `test_parse_resistance`.
#### `PE-TH-001` / `PE-TH-002` / `PE-TH-003` — `thermal_check.py`
Analizza: P = I_load × drop; Tj = Ta + P·θJA (001 INFO senza θJA o Tj ok; 002 WARNING Tj alto — **non in catalogo `finding_engine`**; 003 I²R shunt).
Skip se: manca I_load (Iout_max non è carico).
- Test: `tests/test_thermal_check.py``test_ldo_without_theta_ja_is_info`, `test_iout_max_is_not_used_as_load`, `test_ldo_hot_tj_is_warning`, `test_shunt_over_rating_is_warning`, `test_led_resistor_within_rating_is_silent`.
#### `PE-PWR-001` (schema) — `power_margin_check.py`
Analizza: Σ IQ + I_load vs Iout regolatore; caduta su R serie. Source `power_margin_check`.
Skip se: manca I_load; IQ assente non è fail.
- Test: `tests/test_power_margin_check.py``test_load_over_iout_max_is_ps_pwr_001`, `test_missing_iq_is_not_guessed_into_margin_fail`, `test_series_r_ir_drop_uses_i_load_not_trace`, `test_no_series_r_does_not_invent_trace_drop`.
#### `PE-SEQ-001` — `sequencing_check.py`
Analizza: PG → EN da note datasheet.
Skip se: niente spec `power_sequence`.
- Test: `tests/test_sequencing_check.py``test_pg_not_tied_to_en_is_warning`, `test_pg_tied_to_en_is_silent`, `test_no_power_sequence_spec_skips_even_if_pg_open`.
#### `PE-FLT-001` / `PE-FLT-002` / `PE-FLT-003` — `filter_check.py`
Analizza: topologia filtro (001), pezzo (002), fc vs ADC / DCR ferrite (003).
Skip se: manca C; pull-up+decoupling non è filtro; DCR ferrite senza limite datasheet.
- Test: `tests/test_filter_check.py``test_rc_reports_fc_info_without_adc_rate`, `test_rc_vs_adc_rate_is_warning`, `test_pullup_plus_decoupling_is_not_a_filter`, `test_missing_c_value_does_not_invent_fc_warning`, `test_pi_and_t_need_l_and_c`, `test_ferrite_dcr_warns_only_with_datasheet_limit`.
#### `PE-XTAL-001` / `PE-XTAL-002` / `PE-XTAL-003` — `crystal_cl_check.py`
Analizza: CL vs C1/C2 (001 coppia; 002 serie/stray; 003 drive). Cstray solo se in specs.
Skip se: niente CL in specs.
- Test: `tests/test_crystal_cl_check.py``test_no_cl_in_specs_is_silent`, `test_series_above_cl_without_stray_warns`, `test_with_stray_mismatch_warns`, `test_simple_project_without_cl_silent`.
#### `PE-LF-001` / `PE-LF-002` / `PE-LF-003` — `lifecycle.py`
Analizza: Obsolete / NRND / RoHS non-compliant.
Skip se: catalogo assente.
- Test: `tests/test_lifecycle_check.py``test_obsolete_is_warning_and_uses_distributor_replacement`, `test_nrnd_is_info`, `test_explicit_rohs_non_compliant_is_warning`, `test_active_is_silent`, `test_rohs_not_applicable_is_not_a_fail`, `test_missing_catalog_and_missing_substitute_are_not_guessed`.
#### `PE-INT-001` — `internal_features_check.py`
Analizza: ESD/pull interni vs net.
Skip se: `internal_features` vuoto (non si indovina open-drain).
- Test: `tests/test_internal_features_check.py``test_listed_open_drain_without_pull_is_warning`, `test_listed_pin_with_pullup_is_silent`, `test_empty_features_does_not_guess_open_drain`.
#### `PE-ESR-001` — `hf_coverage_check.py`
Analizza: copertura HF/ESR (bulk vs 100 n).
Skip se: valore C sconosciuto.
- Test: `tests/test_hf_coverage_check.py``test_bulk_only_is_info_ps_esr_001`, `test_bulk_plus_100n_is_silent`, `test_unknown_cap_value_is_not_guessed`.
#### `PE-ERRATA-001` — `errata_check.py`
Analizza: errata pubblicata vs pull sul pin.
Skip se: MPN sconosciuto o entry senza URL.
- Test: `tests/test_errata_check.py``test_missing_errata_pullup_is_ps_errata_001`, `test_pullup_present_is_silent`, `test_unknown_mpn_and_url_less_entry_are_silent`.
Suite deterministica end-to-end: `tests/test_validation_deterministic_seed.py` `test_deterministic_findings_seeded_and_not_reviewed`; `tests/test_eval_report.py` `test_simple_project_eval_matches_committed_golden`.
### 1.4 Certifier di classe (grafo — schema **e** PCB)
Moduli: `interface_class_check.py` (schema **e** PCB), `hf_bus_class.py` (2.62.0, solo `run_pcb_checks`), `usb_pd_check.py` (2.62.1, solo PCB). Niente geometria. Niente connettore/dispositivo → **silenzio**.
#### USB-C — solo se receptacle USB-C sul grafo
- **`PE-USBC-001`** classe USB2 vs USB3 da BOM/footprint/MPN/net.
- **`PE-USBC-002`** CC1 e CC2.
- **`PE-USBC-003`** Rd 5.1 kΩ ±10% o Rp 56/22/10 kΩ. Skip/INSUFFICIENT se R ignota o CC verso controller senza R.
- **`PE-USBC-004`** VBUS e GND.
- **`PE-USBC-005`** SuperSpeed solo se classe USB3; USB2 = N/A (non ERROR).
Test: `tests/test_interface_class_check.py``test_no_connector_emits_nothing`, `test_usbc_rd_vbus_gnd_certified`, `test_usbc_missing_cc2_is_error`, `test_usbc_wrong_rd_is_error`, `test_usbc_cc_to_controller_without_r_is_insufficient_not_error`, `test_usbc_unknown_r_value_is_insufficient`, `test_usb3_class_without_ss_pairs_is_error`, `test_usb3_with_ss_pairs_is_certified`, `test_missing_vbus_is_error`, `test_simple_project_usbc_not_false_error`, `test_hubaudio_like_usbc_usb2_and_poe_magjack`, `test_usbc_vbus_does_not_invent_usb_500ma`, `test_does_not_use_layout_geometry`, `test_rule_catalog_shared_not_si`.
#### Ethernet — solo se RJ45/MagJack
- **`PE-ETH-001`** classe 10/100 vs GbE. Skip/INSUFFICIENT se velocità assente (non si inventa GbE).
- **`PE-ETH-002`** TX/RX (10/100) o quattro MDI (GbE).
- **`PE-ETH-003`** magnetics se GbE.
- **`PE-ETH-004`** Bob Smith 75 Ω: REVIEW (spesso in MagJack).
Test: `tests/test_interface_class_check.py``test_ethernet_10_100_magjack_no_gbe_magnetics_error`, `test_gbe_without_magnetics_is_error`, `test_gbe_with_magnetics_is_certified`, `test_rj45_without_speed_is_insufficient_not_invented_gbe`.
#### PoE — solo con evidenza PoE (RJ45 nudo = skip)
- **`PE-POE-001`** evidenza PoE.
- **`PE-POE-002`** classe/tipo (802.3af/at/bt, Class n) — mai inventata.
- **`PE-POE-003`** magnetics/isolamento (MagJack o LAN transformer).
- **`PE-POE-004`** (2.62.1) tensione di isolamento solo da numero sourced. Skip senza V.
Test: `tests/test_interface_class_check.py``test_bare_rj45_does_not_invent_poe`, `test_poe_with_evidence_requires_magnetics_isolation`, `test_poe_evidence_on_bare_jack_is_isolation_error`, `test_hubaudio_bom_has_usbc_and_poe_rj45_not_ddr`, `test_run_pcb_checks_skips_absent_interfaces`; `tests/test_pcb_phase_b.py``test_poe_isolation_skips_without_voltage_fact`.
#### DDR — solo se DRAM sul grafo (2.62.0)
- **`PE-DDR-001`** classe DRAM.
- **`PE-DDR-002`** CK, DQS, ≥8 DQ.
- **`PE-DDR-003`** VTT/VREF solo se quei net esistono (altrimenti skip, non VTT inventato).
Test: `tests/test_hf_line_check.py``test_no_ddr_cpu_fpga_on_usb_only_graph`, `test_ddr_present_class_and_nets_skip_invented_vtt`, `test_rule_catalog_hf_ids`.
#### CPU bus parallelo — solo se D/A/controllo esistono (2.62.0)
- **`PE-CPU-001`** presenza bus parallelo.
- **`PE-CPU-002`** ≥8 D/DQ/AD.
- **`PE-CPU-003`** address o AD mux.
- **`PE-CPU-004`** CS/WE/OE (o FMC).
Test: `tests/test_hf_line_check.py``test_cpu_parallel_bus_only_when_data_addr_control_exist`.
#### FPGA — solo se FPGA sul grafo (2.62.0)
- **`PE-FPGA-001`** classe FPGA.
- **`PE-FPGA-002`** flash di config se c’è un flash IC (altrimenti skip).
- **`PE-FPGA-003`** VCCINT/VCCIO solo se net nominati.
Test: `tests/test_hf_line_check.py``test_fpga_only_when_present_config_flash_optional`.
#### USB-PD contratto — `usb_pd_check.py` (2.62.1)
- **`PE-PD-001`** controller PD sul grafo (FUSB302/TPS257/…). Non è USB2 Rd. PDO non inventati.
Test: `tests/test_pcb_phase_b.py``test_usb_pd_skips_without_pd_controller`.
### 1.5 Review AI per-IC + post-pass
Moduli: `review_session.py`, `pcb_review.py` non entra qui. DeepSeek, PDF una volta per IC, fail-soft. Prompt tools grafo (`find_connected_components`, `get_net_for_pin`, `get_pintable`, `get_datasheet_excerpt`). Finding LLM = REVIEW, mai RULE ERROR (`finding_engine`).
Skip se: niente MPN; niente PDF (`not_reviewed`); fingerprint invariato (`review_fingerprint.py`).
- Review loop: `tests/test_native_review_loop.py` (5); `tests/test_validation_no_tool_recovery.py` `test_no_tool_calls_triggers_forced_submit_next_turn`; `tests/test_validation_concurrency.py` (3); `tests/test_validation_trace_log.py` (3); `tests/test_review_parse.py` (2); `tests/test_quote_verify.py` (5); `tests/test_finding_engine.py` (`test_llm_review_is_never_rule`, `test_review_and_risk_cannot_stay_error`, `test_insufficient_evidence_does_not_stay_error`); `tests/test_fase_b_checks.py` `test_llm_error_review_clamped_in_complete_finding`; `tests/test_review_fingerprint.py` (2); `tests/test_reprocess.py` (4); `tests/test_deepseek_provider.py` (`test_thinking_only_echoes_reasoning_content_on_follow_up` e roundtrip tool).
- Excerpt cross-IC: `tests/test_datasheet_excerpt_tool.py` (12); `tests/test_cache_breakpoint_limit.py` (3).
- **Normalize** (downgrade-only): `tests/test_normalize_findings.py` (14); `tests/test_periscope_postpass_rewrite.py` `test_emmaforo_uart_normalize_cannot_promote_warning`.
- **Dedupe** cross-IC: `tests/test_dedupe_findings.py` (11); `tests/test_periscope_postpass_rewrite.py` `test_emmaforo_uart_dedupe_collapses_both_endpoints`.
---
## 2. Esame PCB (`MODE=pcb`)
Stadi: `ensure_graph``parse_pcb``classify``inventory`**`run_pcb_checks`** → `ai_review``pcb_report.json`. ID finding `PCB-{ref}-{001}`. Mutex vs analisi schema e vs placement. Inventario net (`pcb_inventory.py`) è numeri, non finding.
KiCad DRC **non** è un nodo Periscope. `tests/test_pcb_software_bugs.py` `test_drc_unconnected_items_count` e `test_hubaudio_pcb_lay004_vs_drc_order_of_magnitude` servono solo a **non** copiare il DRC.
Suite orchestrazione: `tests/test_pcb_review.py` `test_run_pcb_checks_assigns_pcb_ids_and_recommendations`, `test_pcb_pipeline_imports_build_placement_plan`; `tests/test_pcb_phase_b.py` `test_run_pcb_checks_phase_b_absent_is_silent`, `test_phase_b_rule_catalog`; `tests/test_interface_class_check.py` `test_merge_drops_duplicate_pcb_interface_findings`; `tests/test_pcb_sse_terminal.py` (4).
### 2.1 Layout ingest (non DRC)
`parsers_kicad_pcb.py``LayoutGraph`. Nessun default 1 oz.
- Test: `tests/test_kicad_pcb.py` (14); `tests/test_pcb_via_not_pad.py` (geometria via≠pad); `tests/test_pcb_software_bugs.py` `test_kicad10_name_only_nets_fill_index`.
### 2.2 Net / footprint — `pcb_net_match.py` + `pcb_checks._incomplete_layout_finding`
#### `PE-LAY-001`
Pad PCB su net diverso dallo schema (stesso pin).
Skip se: layout assente.
- Test: `tests/test_pcb_review.py``test_pad_net_mismatch_is_pe_lay_001`, `test_hierarchy_plus_real_mismatch_keeps_only_real_pe_lay_001`.
#### `PE-LAY-002`
Ref in schema, nessun footprint (tranne #PWR). Distingue “manca sulla PCB”.
- Test: `tests/test_pcb_review.py` `test_missing_footprint_is_pe_lay_002`; `tests/test_incomplete_pcb.py` `test_unplaced_ref_is_lay_002_not_invented_xy`.
#### `PE-LAY-003`
Stesso net, solo prefisso `/sheet/` KiCad (INFO, una volta).
- Test: `tests/test_pcb_review.py` `test_kicad_hierarchy_slash_is_one_sync_finding_not_per_pad`.
#### `PE-LAY-004` — `pcb_checks.py` (**non in catalogo `finding_engine`**)
Pad net senza rame (track **o** via **o** zone). Skip NC `unconnected-(…)`. INFO INSUFFICIENT, non FAIL inventato.
- Test: `tests/test_incomplete_pcb.py` `test_run_pcb_checks_on_partial_layout_does_not_invent_tracks`; `tests/test_pcb_software_bugs.py``test_lay004_zone_counts_as_copper`, `test_lay004_skips_unconnected_nc_and_matches_sheet_prefix`, `test_hubaudio_pcb_lay004_vs_drc_order_of_magnitude`.
### 2.3 Placement vs `layout_rules` — `placement_check.py`
Senza mm in `layout_rules`: skip. Niente 3 mm default. Distanza euclidea pad-pad **non** usata.
#### `PE-PLC-001`
Path rame (segmenti) vs `max_distance_mm`.
- Test: `tests/test_placement_check.py``test_crystal_load_cap_beyond_max_distance_mm_is_ps_plc_001`, `test_crystal_load_cap_within_max_distance_mm_is_silent`, `test_track_path_longer_than_max_distance_mm_is_ps_plc_001`; `tests/test_pcb_review.py` `test_close_decoupling_has_no_plc_001`; `tests/test_placement_check.py` `test_simple_project_without_pcb_has_no_ps_plc`.
#### `PE-PLC-002`
Via in courtyard vs `min_via_count`. Skip senza vertici courtyard e senza min.
- Test: `tests/test_placement_check.py` `test_via_count_is_calculated_from_courtyard_and_min_parameter` (geometria `_in_poly`; non emette ancora il finding end-to-end).
#### `PE-PLC-003`
`same_layer` decoupling.
- Test: `tests/test_placement_check.py``test_same_layer_param_opposite_layers_is_ps_plc_003`, `test_same_layer_param_same_copper_is_silent`, `test_opposite_layers_without_same_layer_param_is_silent`, `test_opposite_layers_with_via_in_courtyard_is_silent`.
#### `PE-PLC-004`
Keepout: net estraneo nel courtyard. Non è DRC rame-pad.
- Test: `tests/test_placement_check.py``test_keepout_foreign_track_in_courtyard_is_ps_plc_004`, `test_ic_courtyard_pad_nets_are_not_keepout_violations`, `test_keepout_own_net_in_courtyard_is_silent`, `test_keepout_without_courtyard_is_silent`.
#### `PE-PLC-005` (**non in catalogo `finding_engine`**)
Proximity non misurabile perché manca la **traccia**.
- Test: `tests/test_placement_check.py` `test_unrouted_crystal_cap_is_insufficient_not_euclidean`.
Schema runner omette i check layout: `tests/test_placement_check.py` `test_schema_deterministic_runner_omits_layout_checks`.
### 2.4 SI — `si_check.py` + ImpedenceFinder
Gate: `layout_rules` kind + `net_class`/quote sul **bus citato**. Skip I2C/GPIO/EN/CC/strap RC. Bus: USB2, USB3, ETH MDI, RGMII, SGMII, DDR3 CLK/DQS/DQ/ADDR, HDMI, PCIe, LVDS; 2.62.0 aggiunge MIPI e clock HF (`bus_class`); XTAL/OSCIN fuori.
Z0: `impedance.py` / `impedance_traces.py`. CPWG → errore, non numero inventato. Senza stackup: skip misura.
Suite gate: `tests/test_si_check.py` `test_skip_i2c_gpio_cc_regn`, `test_i2c_not_checked_as_50_ohm`, `test_simple_project_without_pcb_has_no_ps_si_001`; `tests/test_hf_line_check.py` `test_bus_class_mipi_hf_clk_not_xtal`. Calcolatrice: `tests/test_impedance.py` (20); misura net: `tests/test_impedance_traces.py` (10).
#### `PE-SI-001` length_match / skew coppia
Skip senza mm datasheet.
- Test: `tests/test_si_check.py` `test_length_match_2_5mm_vs_1mm_is_fail`, `test_coverage_mdi_rgmii_ddr3_usb3_gated_not_cross_mapped`.
#### `PE-SI-002` Zavg/min/max vs finestra datasheet
Mai folklore 90 Ω.
- Test: `tests/test_si_check.py` `test_emmaforo_usb_avg_in_window_min_out_is_margin`, `test_coverage_mdi_rgmii_ddr3_usb3_gated_not_cross_mapped`.
#### `PE-SI-003` lunghezza max mm
- Test: `tests/test_si_check.py` `test_coverage_mdi_rgmii_ddr3_usb3_gated_not_cross_mapped`.
#### `PE-SI-004` spacing intra-coppia mm
Skip senza mm. Copertura indiretta nella stessa suite SI gated.
#### `PE-SI-005` piano di riferimento / layer
Skip senza FACT datasheet.
#### `PE-SI-006` conteggio via HS vs min/max datasheet
Skip senza min/max.
#### `PE-SI-008` return via accanto alla coppia (`return_path`)
Skip senza kind.
#### `PE-SI-009` serie R ohm sul net HS (non EN-RC)
- Test: `tests/test_si_check.py` `test_en_rc_series_resistor_does_not_paint_usb`.
#### `PE-SI-010` bus HS misurato, libreria senza FACT Z → INFO, non FAIL 90 Ω
- Test: `tests/test_si_check.py` `test_usb_without_library_z_is_insufficient_not_90ohm_fail`, `test_empty_net_class_impedance_does_not_paint_usb`; `tests/test_hf_line_check.py` `test_existing_si_usb_not_polluted_by_hf_geometry`.
Refresh extract SI vecchio: `tests/test_pcb_plan_closeout.py` `test_si_refresh_when_old_extract_has_only_decoupling`, `test_si_extract_needed_skips_board_ics_only_not_shared_library`.
### 2.5 Linee HF extra — `hf_line_check.py` (2.62.0 Fase A)
Track ≠ via ≠ pad ≠ zona. Stub = traccia dangling.
#### `PE-SI-007` stub vs mm datasheet
INFO se misura c’è e mm mancano (INSUFFICIENT). Skip: pad-pad, via, zone.
- Test: `tests/test_hf_line_check.py``test_no_layout_skips_hf_geometry`, `test_pad_to_pad_usb_has_no_stub`, `test_via_is_not_a_stub`, `test_zone_is_not_a_track_stub`, `test_dangling_track_stub_vs_datasheet_mm_is_fail`, `test_measured_stub_without_datasheet_mm_is_insufficient`.
#### `PE-SI-011` gap pour GND sotto coppia HF (REVIEW)
Skip senza stackup/zone.
- Test: `tests/test_hf_line_check.py` `test_split_under_pair_needs_stackup_and_zone`.
#### `PE-SI-012` terminazione BOM serie/parallelo FACT
Skip se manca il terminatore (non si inventa 50 Ω).
- Test: `tests/test_hf_line_check.py` `test_bom_termination_is_fact_missing_is_skip`.
Catalogo HF: `tests/test_hf_line_check.py` `test_rule_catalog_hf_ids`. DDR/CPU/FPGA: §1.4 (stesso `check_memory_fpga_classes` in `run_pcb_checks`).
### 2.6 Potenza / via / termico sul board — `pcb_power_thermal.py`
#### `PE-PWR-001` (PCB) — `check_pcb_power_traces`
Larghezza **traccia** × spessore rame vs I_load/Imax/I_abs. IPC-2221 solo con thickness **e** ΔT da Tjmax. Iout_max non è carico. Niente 500 mA USB.
Skip se: manca I datasheet (**skip vero**, non INFO INSUFFICIENT — 2.61.1).
- Test: `tests/test_pcb_review.py``test_power_trace_ipc2221_errors_when_load_exceeds_ampacity`, `test_power_trace_uses_parsed_width_and_thickness`, `test_power_trace_skips_without_i_load`, `test_power_trace_skips_iout_max_as_load`, `test_power_trace_uses_imax_when_i_load_absent`, `test_power_trace_uses_i_abs_when_i_load_absent`; `tests/test_interface_class_check.py` `test_usbc_vbus_does_not_invent_usb_500ma`.
#### `PE-VIA-001` — `check_pcb_via_current`
Se I c’è e sul net **zero via**: INFO conteggio. Se le via ci sono: silenzio — **nessuna tabella ampacity**. Via ≠ traccia.
Skip se: manca I.
- Test: `tests/test_pcb_software_bugs.py` `test_via_current_skips_without_i_load`.
#### `PE-VIA-002` (2.62.1)
I + conteggio/drill FACT. Tabella IPC via **non** applicata.
Skip se: manca I.
- Test: `tests/test_pcb_phase_b.py` `test_via_current_skips_without_i_does_not_invent_ipc`.
#### `PE-THM-001` — `check_pcb_thermal_copper`
P = I_load × drop; courtyard senza pour/via.
Skip se: P sconosciuta.
- Test: `tests/test_pcb_review.py` `test_thermal_copper_warns_without_pour_or_vias`.
#### `PE-THM-002` — `check_pcb_junction_temp`
Tj = Ta + P·θJA solo con P, θJA, area rame, conteggio via. Non è FEM.
Skip/INSUFFICIENT se manca un fattore.
- Test: `tests/test_pcb_plan_closeout.py``test_tj_when_theta_copper_vias_exist`, `test_tj_insufficient_without_theta`.
#### `PE-KEL-001`
Pin Kelvin/sense sullo stesso net di carico. Ignora CRS/IN±.
- Test: `tests/test_pcb_review.py` `test_kelvin_sense_pin_on_shared_net`; `tests/test_pcb_software_bugs.py` `test_kelvin_ignores_crs_and_in_plus`.
#### `PE-STCH-001`
Segnale sopra pour GND senza via GND nel bbox. Skip GPIO minuscoli.
- Test: `tests/test_pcb_review.py``test_gnd_stitch_skips_tiny_gpio`, `test_gnd_stitch_info_when_signal_has_pour_but_no_via`.
### 2.7 Derating / gerarchia / timing / PI
#### `PE-DRT-001` / `PE-DRT-002` / `PE-DRT-003` — `pcb_checks.check_pcb_derating` + `derating.py`
Vop vs Vrated: ERROR / MARGIN / PASS INFO. Niente % dielettrico inventato. Skip se manca Vop o Vr.
- Test: `tests/test_fase_b_checks.py` `test_derating_pass_margin_risk`; `tests/test_derating.py` (7, C_eff stima — non è un PE-* a parte).
#### `PE-HIER-001` — `hierarchy.py`
Pin IC senza net nominato.
- Test: `tests/test_fase_b_checks.py` `test_hierarchy_component_pin_net_block`.
#### `PE-TIM-001` / `PE-TIM-002` — `timing_check.py`
001 RC reset vs t_reset; 002 strap vs Vih/Vil.
Skip senza R/C e t_reset o Vih/Vil.
- Test: `tests/test_fase_b_checks.py``test_timing_skips_without_numbers`, `test_timing_reset_rc_vs_t_reset`. **`PE-TIM-002` non ha un test che fa scattare il finding** (solo skip condiviso).
#### `PE-PI-001` / `PE-PI-002` — `pi_check.py`
001 cap locale sul rail IC; 002 locale vs bulk se i valori C esistono. Distanza mm solo da `layout_rules` (altrimenti è PE-PLC-001). Skip net NC.
- Test: `tests/test_fase_b_checks.py``test_pi_missing_local_is_risk_not_error`, `test_pi_any_cap_on_slash_prefixed_rail_suppresses_missing_local`, `test_pi_bulk_only_does_not_claim_no_local`; `tests/test_pcb_software_bugs.py` `test_emi_and_pi_skip_unconnected_nets`. **`PE-PI-002` non ha un assert dedicato sul `rule_id`.**
### 2.8 ESD / return / EMI / SPOF
#### `PE-ESD-001` — `esd_return_check.check_esd`
Net J* ∩ IC senza parte ESD: REVIEW, non ERROR. Niente GPIO/NC/rail spam.
- Test: `tests/test_fase_b_checks.py``test_esd_without_part_is_review_not_error`, `test_esd_skips_gpio_nc_unconnected_and_onboard_power`, `test_esd_one_finding_per_connector_ic_path`, `test_esd_skips_when_protection_part_on_net`.
#### `PE-ESD-002` (2.62.1) — `check_esd_distance`
Distanza **pad** TVSconnettore (via ≠ pad). INFO se no mm.
- Test: `tests/test_pcb_phase_b.py` `test_esd_distance_uses_pads_not_vias`.
#### `PE-RET-001` — `check_return_path`
Net HS sopra pour GND senza via GND nel bbox: REVIEW.
- Test: `tests/test_fase_b_checks.py` `test_return_path_hs_is_review`.
#### `PE-EMI-001` — `emi_check.py`
Solo se `layout_rules` cita choke/ferrite/shield. Non IEC 61000. Skip NC.
- Test: `tests/test_pcb_plan_closeout.py` `test_emi_only_with_datasheet_fact`; `tests/test_pcb_software_bugs.py` `test_emi_and_pi_skip_unconnected_nets`.
#### `PE-SPOF-001` — `spof_check.py`
Un regolatore o XTAL condiviso: REVIEW, mai ERROR.
- Test: `tests/test_pcb_plan_closeout.py` `test_spof_review_single_ldo`.
### 2.9 BOM ↔ PCB ↔ datasheet — `bom_pcb_check.py`
Skip se manca un lato (BOM, footprint, o numero datasheet).
#### `PE-BOM-010` famiglia package
VQFN/WQFN/HVQFN = QFN. LQFP ≠ QFN.
- Test: `tests/pcb/test_pcb_plan_closeout.py` `test_package_family_mismatch_is_pe_bom_010`; `tests/pcb/test_bom_011_named_join.py` `test_qfn_vs_vqfn_same_24_qfn_land_not_bom_010`.
#### `PE-BOM-011` pintable vs pad, join per nome
Join datasheet pintable × `.kicad_mod` lib × pad embedded. Non `pin_count` scalare. A5/B5 USB-C sono pin, non EP. EP/SH/mount classificati; via ≠ pad. Senza pintable: skip.
- Test: `tests/pcb/test_bom_011_named_join.py`; `tests/pcb/test_pcb_plan_closeout.py` `test_package_family_mismatch_is_pe_bom_010`; `tests/pcb/test_pcb_software_bugs.py` `test_ep_split_pads_not_bom_011`; `tests/pcb/test_pcb_via_not_pad.py`.
#### `PE-BOM-012` Vop vs rating/abs-max legato al **pin**
- Test: `tests/test_pcb_plan_closeout.py` `test_abs_max_voltage_and_temp_and_current`; `tests/test_pcb_software_bugs.py` `test_vddcr_absmax_does_not_bind_3v3_io`.
#### `PE-BOM-013` Top vs abs-max T
- Test: `tests/test_pcb_plan_closeout.py` `test_abs_max_voltage_and_temp_and_current`.
#### `PE-BOM-014` I_load vs rating
Skip se manca I.
- Test: `tests/test_pcb_plan_closeout.py``test_abs_max_voltage_and_temp_and_current`, `test_inductor_current_rating`.
### 2.10 Resto Fase B (2.62.1)
#### `PE-STK-001` — `stackup_check.py`
Spessore rame board vs stackup fab sourced. Mai 1 oz default.
Skip se: niente stackup layout o niente FACT fab.
- Test: `tests/test_pcb_phase_b.py``test_stackup_skips_without_fab_spec`, `test_stackup_vs_fab_spec_is_review_not_invented_oz`.
#### `PE-ANT-001` / `PE-ANT-002` — `antenna_layout_check.py`
Keepout zona e matching L/C sul feed. Solo se antenna/net RF sul grafo. Niente 50 Ω inventati.
Skip se: antenna assente; matching manca e non c’è FACT (002 non emette).
- Test: `tests/test_pcb_phase_b.py``test_antenna_skips_when_absent`, `test_antenna_keepout_and_match_are_facts`.
#### `PE-PDN-001` — `pdn_check.py`
Z(f) solo con FACT in frequenza. Z0 SI **non** è PDN.
- Test: `tests/test_pcb_phase_b.py` `test_pdn_skips_without_zf`.
Silenzio Fase B se assente: `tests/test_pcb_phase_b.py` `test_run_pcb_checks_phase_b_absent_is_silent`. Catalogo: `test_phase_b_rule_catalog`.
### 2.11 Review AI PCB
Modulo: `pcb_review.py` + `services/pcb_validation.py`. Stesso oggetto finding. Spiega FACT deterministici; **non** rilegge il PDF; non inventa interfacce / PoE / SuperSpeed / mm / Z / I.
Skip se: niente JSON libreria per lIC.
- Test: `tests/test_pcb_review.py``test_pcb_ai_finding_gets_action`, `test_parse_review_action_field_without_recommendation`, `test_layout_context_includes_via_counts`, `test_layout_context_includes_domain_and_group`, `test_pcb_ai_skips_without_library_extraction`, `test_library_constraints_fill_from_storage`, `test_inventory_lists_net_length_and_pair`; `tests/test_finding_engine.py` `test_pcb_review_ai_finding_action_without_recommendation`; `tests/test_pcb_software_bugs.py` `test_thinking_reasoning_content_echo_still_present`.
### 2.12 Tab antenna RF (non in `run_pcb_checks`)
Moduli: `antenna_rf.py`, `antenna_geometry.py`. Topologia matching + ricetta routing. No EM/VSWR/CPWG. Distinto da `PE-ANT-001/002`.
- Test: `tests/test_antenna_rf.py``test_verify_finds_matching_path_to_ant_footprint`, `test_verify_missing_matching_is_warning`, `test_design_recipe_needs_marker_without_ant`, `test_design_recipe_ready_with_ant_and_stackup`, `test_geometry_templates_produce_export`, `test_geometry_overflow_tiny_zone`, `test_design_recipe_meander_template`.
Placement/auto-place **non** è esame PCB: `tests/test_placement_pack.py`, `tests/test_placement_pipeline.py` (fuori da questo albero di analisi).
---
## Motore finding (condiviso)
`finding_engine.py`: FACT / REQUIREMENT / INFERENCE; ERROR solo RULE+MANDATORY; `decisions.json` non ri-naga.
- Test: `tests/test_finding_engine.py` (11); `tests/test_finding_schema.py` (7); `tests/test_fase_b_checks.py` `test_sort_findings_error_then_class`; `tests/test_review_workflow.py` (10 — stati finding UI, non check PE). CAD bridge: `tests/test_cad_bridge.py` (5).
---
## Test che esistono ma non sono analisi
`tests/` ha **114 file / ~730 test**. Oltre ai nodi sopra restano overlay nativi, upload, auth, billing seam, UI rewrite. Non sono check PE-*.
**Upload / ingest cartella** (non analisi): `tests/test_periscope_frontend_upload_rewrite.py` `test_upload_zone_is_src`; `tests/test_kicad_project.py` (picker cartella, `.history`, Safari stem); `tests/test_netlist_bundle.py` (zip, zip-slip); `tests/test_kicad_pcb.py` `test_upload_pcb_sets_has_pcb`, `test_upload_sch_as_pcb_is_rejected`; `tests/test_purple_parts_resolver.py` (upload BOM/LCSC); `tests/test_reopen_replace.py` `test_reopen_then_replace_bom_and_netlist`.
**Auth**: i test auth esistono (`tests/test_local_auth.py`, `tests/test_periscope_auth_rewrite.py`, `tests/test_pinscope_compat.py`, più overlay che tengono il contratto login). Non si descrivono segreti, JWT, password, o flussi di autenticazione.
Altri non-analisi: rewrite frontend/Docker (`test_periscope_*_rewrite.py`, `test_periscope_leftover_package_requirements.py`, `test_periscope_boot_without_dependency_product.py`); delete progetto; cost estimator; event bridge; job runner; `test_deepseek_only.py` (routing modello, non finding).
---
## Conteggio nodi
| Gruppo | Nodi |
| --- | --- |
| Check solo schema (27 PE-* + LED senza ID) | 28 |
| USB-C / ETH / PoE (schema e PCB) | 13 |
| `PE-PWR-001` (due source: schema e PCB) | 1 |
| DDR / CPU / FPGA / PD (grafo, invocati da `run_pcb_checks`) | 11 |
| Check solo PCB (layout, SI/HF, potenza, Fase B, …) | 47 |
| Processo: 3 skill + DigiKey + value + IC AI + PCB AI + tab RF | 8 |
| **Totale nodi analisi** | **108** |
Check PE-* in codice: **99** (tutti elencati). Più LED senza `rule_id`. `PE-LAY-004`, `PE-PLC-005`, `PE-TH-002` sono in codice; `PE-LAY-004` / `PE-PLC-005` non sono in `_seed()` di `finding_engine.py`.
Buchi di test noti (il check c’è, il fire test no): `PE-TIM-002`, `PE-PI-002` (nessun assert `rule_id`), `PE-PLC-002` (solo geometria `_in_poly`), `PE-SI-004` / `PE-SI-005` / `PE-SI-006` / `PE-SI-008` (gate SI, niente caso dedicato).
+142
View File
@@ -0,0 +1,142 @@
# Conformità coding — Periscope intero
Percorso locale: `/Users/michelebigi/Development/periscope/docs/conformita-coding.md`.
Costituzione: `docs/development/CODING_CONSTITUTION.md` (*code that fits in your head*). **Per sezione**, non per funzione: conforme sì / no e perché. Taglio 2.62.1 + questa macro-fase (libreria come porta, test riorganizzati, AF+AI extra). Auth/JWT/users: **non toccati**; la sezione esiste e viene giudicata, non modificata.
Giudizio: **conforme** = un ingegnere legge la sezione senza ricostruire un sistema nascosto. **Non conforme** = troppe responsabilità, stato implicito, eccezioni ingoiate, o semantica a rischio. Un file lungo può essere conforme se il flusso è ovvio; uno corto no se fa tre mestieri.
Zero eccezioni al principio. Le sezioni “non conformi” restano debito: non si “passa” la costituzione dichiarandole OK.
---
## 1. Albero nativo / dependency
**Non conforme.** `periscope/src` (nativo) e `periscope/dependency` (PinScope ereditato) si fondono con `sys.path` + `pkgutil.extend_path`. Chi vince dipende dallordine di insert (`backend/__init__.py` vs `tests/conftest.py`). Due `projects.py`, due `pipeline.py`, due `extraction.py`. Per capire un import serve la mappa dei shadow, non il modulo. È un adattatore temporaneo con path di rimozione (Fase C) ma **oggi** non sta in testa.
## 2. Glue di root (Docker, compose, `backend/__init__.py`, script)
**Conforme a metà.** `backend/__init__.py` è corto e dice il mestiere. `scripts/update-periscope.sh` è una procedura esplicita (`/root/periscope`, niente `data/`). `docker-compose.yml` è piccolo. Il debito è il merge dei due tree a boot, non gli script.
## 3. Motore finding (`periscopex/finding_engine.py`, schema)
**Conforme.** Un oggetto finding, FACT / REQUIREMENT / INFERENCE, clamp verso il basso, `INSUFFICIENT`. Flusso visibile. Test stretti su tipo, codice, severity. ~450 righe: lungo ma un mestiere.
## 4. Modello semantico (`models.py`)
**Conforme.** Pad, via, track, zone, pin, net sono tipi distinti. Pydantic, niente god-class UI. ~534 righe di dati, non di orchestrazione.
## 5. Parser schematico (PADS, EDIF, KiCad sch)
**Conforme a metà.** Funzioni pure, fixture `simple_project`. `parsers_kicad.py` (~760) e `parsers_edif.py` (~465) sono grandi; il mestiere resta “testo → grafo”. Non classificano via PCB come pad (coperto da test rewrite). Debito: taglia dei file, non la semantica.
## 6. Parser PCB KiCad (`parsers_kicad_pcb.py`)
**Conforme.** Via ≠ pad è esplicito e testato. Un input `.kicad_pcb``LayoutGraph`. Non è DRC. ~446 righe.
## 7. Grafo (`graph.py`, `netlist_bundle.py`)
**Conforme.** Costruzione da BOM+netlist, helper di attraversamento. Ferrite Z è un innesto a parte (`ferrite_z.py`), non un if U1.
## 8. Check deterministici PCB (`pcb_checks.py` + moduli `PE-*`)
**Conforme nel disegno, non nel dispatcher.** Ogni modulo (`si_check`, `hf_line_check`, `stackup_check`, …) ha un mestiere e skip senza evidenza. `run_pcb_checks` è un elenco esplicito — si legge. **Non conforme:** `except Exception: log + skip` per ogni check (fallimento strumento vs finding vs dati, collassati). `pcb_power_thermal.py` (~748) e `si_check.py` (~862) e `interface_class_check.py` (~831) sono al limite: ancora un dominio, ma non “piccoli moduli”.
AF Board+AI (`af_ai_hf.py`) è **additivo**: `pcb_pipeline` chiama `append_investigated` dopo `run_pcb_checks`. Non entra nella lista 2.62.1. Non è DRC.
Non è DRC (clearance/track_width/annular restano KiCad). FEM assente: **conforme al vincolo**.
## 9. Check schematico (derating, LED, crystal, mux, rail, …)
**Conforme.** Un file ≈ un check, grafo in → finding out, niente mm inventati. Alcuni file >400 righe (`passive_rail_check`, `filter_check`) ma il flusso è lo stesso.
## 10. Review AI (validate, pcb_review, review_tools)
**Non conforme come sezione unica.** Lautorità deterministica è nei check; lLLM spiega — questo è il disegno giusto (costituzione §8). In pratica `review_tools.py` (~940) e `validation.py` (dependency + native) sono loop di tool + state. `pcb_review.py` (~327) è il prompt + vicinato: quello sta in testa. Il loop live dipende ancora da pezzi ereditati. AF+AI (ipotesi HF → indagine deterministica) è un modulo extra, non sostituisce `run_pcb_checks`.
## 11. Estrazione datasheet (skills, `datasheet_extract.py`, `extraction.py`)
**Non conforme.** `datasheet_extract.py` ~1322 righe e `extraction.py` ereditato ~1298: prompt, tool, coerce, taxonomy, auto-resolve nello stesso file. Il mestiere “PDF → JSON libreria” è uno, limplementazione no. Native vs inherited duplicato finché il pipeline non switcha. **Conforme nel ruolo:** LLM estrae, non è il verificatore.
## 12. Libreria componenti (store + porta HTTP/UI)
**Prima: non conforme come porta.** Catalogo e `library_has_*` vivevano in `services/projects.py` (CRUD progetti + libreria). La pagina `/library` era sola lettura e lempty state mandava a “crea un progetto e lancia la review”. Admin `/admin/components` mescola libreria e users.
**Dopo 2.63.1: conforme come porta.** `POST /api/library/datasheets` registra una scheda (inbox IC o modello passivo/discreto) senza esame. Pintable vuota non va in `library/extracted/` (`library_gate`). PUT promuove inbox → extracted. `projects.py` re-export resta debito. `list_library_catalog` logga e salta JSON rotti.
## 13. Pipeline orchestrazione (`pipeline.py`, `pcb_pipeline.py`, job)
**Non conforme.** `pipeline.py` ~1522 righe: stage, storage, LLM, copy-in-library, graph. `pcb_pipeline.py` è più lineare (ensure_graph → parse → checks → **af_ai additivo** → AI → report) e si segue. Job/SSE sono un secondo asse di stato. Flusso reale: sì, ma non locale. `run_pcb_checks` 2.62.1 non è stato svuotato.
## 14. Storage (`storage.py`, GCS)
**Conforme.** Backend con chiavi stringa, locale vs GCS. Prefissi `users/…/projects/` e `library/` visibili.
## 15. HTTP — progetti, pipeline, report, impedance
**Non conforme per `routers/projects.py` (~1004)** e `pipeline.py` router (~783): troppi mestieri (CRUD, upload KiCad, DigiKey, LCSC). Report e impedance sono sezioni più piccole. La nuova `routers/library.py` è la porta libreria (un mestiere).
## 16. Auth / JWT / users
**Non toccata in questa macro-fase (vincolo).** La sezione **non è conforme** alla costituzione (Clerk + JWT locale + `admin.py` users nello stesso router, middleware che decide tre modi). Non si “sistema” qui. Non si aggiunge auth alla libreria.
## 17. Frontend — shell e pagina libreria
**Conforme a metà.** Overlay `src` su `dependency` (materialize) è un secondo albero da tenere in testa. Pagine progetto/report/dashboard sono lunghe ma a mestiere. `/library` era browse-only; ora è porta (import + modifica scheda) con form/editor spezzati. `admin/page.tsx` ~1780: **non conforme** (libreria + users + usage). Non toccato (users).
## 18. Frontend `api.ts` / types
**Non conforme.** `api.ts` nativo ~1179 righe, client unico per tutto. Types allineati ai modelli: sì. Un file non sta in testa. Nuove funzioni libreria restano lì per non inventare un secondo client.
## 19. Skills e taxonomy
**Conforme.** `skills/*/SKILL.md` + `validate.py` in-process; taxonomy JSON per tipo. `repo_paths` al posto di `Path(__file__)` magici (test rewrite). Non si chiama `upload_skills.py`.
## 20. Vendor ImpedenceFinder
**Conforme come confine, non come licenza.** Core Z0 chiuso, non FEM, non secondo set di formule (test). LICENSE UNKNOWN resta debito legale, non di forma del codice.
## 21. Test
**Prima: non conforme come mappa.** Un flat `tests/test_*.py` mescolava datasheet, libreria, schema, PCB, rewrite, auth. Copertura vera, ordine mentale no.
**Dopo: conforme come mappa, copertura tenuta.**
| Cartella | Mestiere |
| --- | --- |
| `tests/datasheet/` | preliminare PDF / pin / abs-max / I / Z / ferrite / DigiKey |
| `tests/library/` | porta libreria (anche senza esame) |
| `tests/schematic/` | net, BOM, review IC, check su grafo |
| `tests/pcb/` | `run_pcb_checks`, geometria, SI/HF già in 2.62.1 |
| `tests/impedancefinder/` | vendor Z0 (stesso nome package del vendor — non va sotto `pcb/`) |
| `tests/af_ai/` | extra: ipotesi HF → indagine deterministica (non DRC, no Z inventata) |
| `tests/` root | identity/rewrite/auth/job — non analisi |
`conftest.py` e `paths.py` restano in root. Test stretti (codice finding, via≠pad) restano la regola; i rewrite “il file sta in src” sono deboli ma sono recinti di albero, non di fisica.
## 22. Costituzioni Cursor (`.cursor/rules`, questo doc)
**Conforme.** Un master Markdown, `.mdc` operativi, niente Rust speculativo. Questo file è il giudizio, non una seconda costituzione.
## 23. Git / deploy
**Conforme al testo, fragile in pratica.** Commit+push a fine fase; deploy a fine macro-fase; no force. Il worktree locale era un pointer a `~/Development/pinscope` sparito: history recuperata da `github` `cursor/pcb-hf-analisi-675d` @ `20733f0` (2.62.1). Non si tocca `~/Development/pinscope` per edit di prodotto.
---
## Sintesi
| Sezione | Conforme |
| --- | --- |
| Finding engine + modelli + parser PCB | sì |
| Check PE-* come moduli | sì (dispatcher fail-soft no) |
| Skills/taxonomy/storage/Z0 vendor | sì |
| Dual tree src/dependency | no |
| Pipeline + extract ~1.3k + projects router | no |
| Auth/admin users | no (non toccare) |
| Libreria come porta | sì dopo questa fase (re-export debito) |
| Test a cartelle di mestiere | sì dopo questa fase |
Priorità debito (non questa fase): spezzare `pipeline.py` / `datasheet_extract.py`; togliere lo shadow dependency quando un modulo nativo è provato; non ingoiare Exception nei check PCB (distinguere tool failure).
**Niente Rust in questa macro-fase** — vedi `docs/rust-criteri.md`. FEM fuori. DRC = KiCad.
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
# Libreria componenti — porta prodotto
La libreria **non** vive dentro lesame. È una porta a sé: pagina `/library` + API `/api/library`. Lanalisi *usa* la libreria; non è lunico modo per riempirla.
## Flusso
```text
PDF + MPN + kind (ic | passive_part | simple)
POST /api/library/datasheets
blob MD5 + ref MPN
scheda componente
IC → library/inbox/{mpn}.json (niente pintable inventata)
passive_part → library/passives/{mpn}.json
simple → library/models/{mpn}.json
```
Nessun progetto, nessun `MODE=run` / `MODE=pcb`. Stesso store `library/datasheets/{blobs,refs}`.
`library/extracted/` si scrive **solo** con pintable valida (`library_gate`: ≥2 pin, almeno un nome). PUT `/api/library/components/ic/{mpn}` promuove inbox → extracted.
Pintable IC: `library_gate` rifiuta pintable vuota o senza nomi (niente stub in libreria condivisa).
## Cosa non è
- Non è admin/Clerk/JWT (non si tocca auth).
- Non è DRC, non è FEM.
- Non inventa pin dal PDF. LLLM prelim resta un mestiere a parte; la scheda c’è comunque.
- Non sostituisce `library_has_*` usati dalla pipeline (`library_has_extraction` resta falso finché non c’è pintable).
## Test
`tests/library/` — catalogo, alias MPN, import PDF senza progetto (scheda IC in inbox, passivo in passives), GET/PUT scheda, promozione pintable, rifiuto PDF non valido / kind ignoto.
+154
View File
@@ -0,0 +1,154 @@
# Piano di implementazione: analisi AF della traccia (v1)
DRC = KiCad. Periscope = analisi. **Stesura ora = Python.** Niente rustup, Auth/JWT, OpenEMS, FEM 3D, field solver 2.5D. Pad ≠ via ≠ track ≠ zone. Non si inventano Z, I, mm, εr, tr, f.
Michele 2026-09-22: piano ok con correzioni sotto. SI/HF 2.62 e `PE-AF-001` restano **additivi**. ImpedenceFinder vendored (`vendor/impedancefinder`) non si riscrive.
Repo: `~/Development/periscope`. Copia di questo file anche in `docs/piano-af-analisi.md`.
---
## Paletti obbligatori (Michele)
1. **Z target solo da datasheet** (`z0_ohm` / `zdiff_ohm` / finestra `z_min``z_max` in `layout_rules`). Manca → **skip del confronto Z**, finding visibile INSUFFICIENT, **niente 50/90 Ω**.
2. **Coppia differenziale: i due membri insieme** (Zdiff, accoppiamento intra-coppia, lunghezze/skew). Mai una traccia sola se esiste il partner `_P/_N` o `+/-` sulla board.
3. **Simulazione numerica sì, OpenEMS no.** Niente FEM 3D né solver di campo 2.5D della spec. Metodo contenuto: sezioni da ImpedenceFinder Z0(x) → RLGC lossless per sezione → cascade ABCD → S11/S21 **solo se** Z_ref (= target datasheet) è FACT.
4. **C++ vs Rust:** valutati in §15. Implementazione v1 in Python. Niente rustup.
5. **Skip AF non silenziosi.** In report: *«Pista ad alta frequenza non controllata per mancanza di …»* (tr, f, εr, stackup, Z target datasheet, span via). Finding **INSUFFICIENT / REVIEW**. Non INFO con Z/I inventati. **Se il trigger è falso** (calcolato con FACT e `l` sotto soglia) → **niente finding** AF su quella net/coppia.
---
## 1. Perimetro vs spec
La spec (`specifica-af.md`) descrive Gerber/ODB++, field solver 2.5D, S/TDR completi. Periscope esamina `.kicad_pcb` + grafo + libreria.
| Spec | v1 Periscope |
| :--- | :--- |
| Parser Gerber/ODB++ | No. KiCad `LayoutGraph`. |
| Trigger λ/10 e tr/(6 tpd) | Sì, FACT only. |
| Gomiti, taper, 3W, piano 3H | Sì, solo net/coppie **triggerate**. Non DRC. |
| Via stub / L_via | Sì se drill + **span layer** + h. Altrimenti PE-AF-002 span via. |
| Field solver 2.5D / OpenEMS | **Fuori.** |
| RLGC + S-param | Cascade sezioni lossless + Z0 ImpedenceFinder. S11/S21 se Z_ref datasheet. |
| TDR IFFT | Fuori. Profilo Z0(x) non si chiama TDR. |
| Wheeler allegato B | Non usato. Hammerstad/Cohn del vendor. |
`run_pcb_checks` (SI/HF) **invariato**.
---
## 2. Trigger
Candidati: net con rame **traccia**, non power/GND, non `skip_si_net` (I2C/GPIO/EN/CC/strap), non XTAL. Coppia = ununità: `l = max(l_p, l_n)`; se un membro è candidato, lo è la coppia.
Costanti: c = 2.99792458×10⁸ m/s. `tpd = √εr_eff / c`. `λ = c / (f √εr_eff)`.
- λ/10 se `f` FACT oppure `f = 0.35/tr` con `tr` FACT, e εr_eff da stackup+geometria (ImpedenceFinder).
- Rise time: `l ≥ tr / (6 tpd)` con `tr` FACT (non la forma tr·vp/2).
**Trigger vero** → analisi discontinuità / Z / cascade / via.
**Trigger falso** (entrambe le soglie calcolate e `l` sotto) → silenzio AF.
**Trigger non calcolabile** su un candidato (manca tr **e** f, o manca stackup/εr) → **PE-AF-002 visibile**, testo italiano con la lista di ciò che manca. Non è “trigger falso”.
---
## 3. Skip visibili (non silenziosi)
| Manca | Testo (es.) | Quando |
| :--- | :--- | :--- |
| stackup / εr | mancanza di stackup, εr | candidato, trigger non valutabile |
| tr, f | mancanza di tr, f | candidato, serve almeno uno |
| Z target datasheet | mancanza di Z target datasheet | trigger **vero**, niente confronto ±10% e niente S |
| span via | mancanza di span via | trigger vero **e** c’è un via sulla net/coppia senza layers |
Niente ohm, niente ampere, niente 1 ns USB. Status WARNING, class REVIEW, `evidence_status=INSUFFICIENT` (il clamp del motore finding non deve promuovere RULE/ERROR).
`PE-AF-001` (AI Z0 senza stackup) resta; è già INSUFFICIENT visibile.
---
## 4. Coppia differenziale
Partner: ImpedenceFinder + `partner_net`. Un finding per coppia, non due cloni. Zdiff da `diff_microstrip_z0` / `diff_stripline_z0`. Intra-coppia: lunghezze, non regola 3W (il mate non è aggressore). 3W solo vs **altre** net.
---
## 5. Simulazione numerica (non OpenEMS)
Per net/coppia triggerata con campioni Z0:
1. Sezioni di lunghezza campionata, Z0 ImpedenceFinder (flag `plane_broken` esclusi dal voto ohm).
2. Lossless: `L' = Z0 · tpd`, `C' = tpd / Z0` per metro.
3. ABCD di cascata; S11/S21 rispetto a **Z_ref = target datasheet**.
4. Confronto ΔZ0 ±10% vs stessa finestra datasheet. Duplicato `PE-SI-002`: non secondo FAIL.
Senza Z_ref: PE-AF-002, cascade non pubblica S.
---
## 6. Dati
- Stackup KiCad già parsato (`epsilon_r`, thickness; mai 1 oz default).
- `LayoutVia.layers` da `(layers "F.Cu" "B.Cu")`. Size anulare ≠ drill ≠ track.
- `tr`/`f` da `layout_rules` del driver sulla net (`rise_time`, `tr_ns`, `f_hz`, …) e `net_class` espanso come SI.
---
## 7. Finding PE-*
| ID | Ruolo |
| :--- | :--- |
| PE-AF-001 | AI Z0 senza evidenza (esistente) |
| PE-AF-002 | Skip visibile “non controllata per mancanza di …” |
| PE-AF-020 | Gomito ~90° |
| PE-AF-021 | Gradino W / taper |
| PE-AF-030 | `plane_broken` |
| PE-AF-031 | Return 3H |
| PE-AF-032 | `plane_split_nearby` |
| PE-AF-040 | 3W vs aggressore (non il mate) |
| PE-AF-050 | Z0/Zdiff vs finestra datasheet + cascade in `calculation` |
| PE-AF-051 | CPWG/unknown: no ohm |
| PE-AF-060 | L_via se drill+h+span |
| PE-AF-061 | Via stub vs λ/20 |
---
## 8. Moduli e pipeline
`af_trigger.py`, `af_rlgc.py`, `af_trace_check.py`. Dopo `run_pcb_checks`, prima `af_ai`. Non dentro la lista 2.62. Stage SSE `af_trace`.
---
## 9. Test HubAudio
Path opzionale `~/Development/HubAudio/.../HubAudio.kicad_pcb`. USB senza tr FACT → PE-AF-002 (tr/f), zero 90 Ω. GPIO → niente AF. Trigger sintetico corto con tr FACT → zero finding. Lunga + target datasheet → PE-AF-050. Coppia: un finding, non D+ solo. SI stub `PE-SI-007` resta.
---
## 10. Fasi v1 (questa implementazione)
Parser via layers; trigger; skip visibili; coppia; Z/cascade se target; gomiti/width; 3W; via se span; pipeline; changelog; pytest.
---
## 11. Fuori scope
OpenEMS, FEM, 2.5D, TDR IFFT, NEXT/FEXT in volt, 5W default, auto-miter sul PCB, Gerber/ODB++, Auth/JWT, rustup.
---
## 15. C++ vs Rust (valutazione; stesura Python)
Criteri (come `docs/rust-criteri.md`): geometria pad≠via≠track≠zone al confine; memoria/ownership su HubAudio; hot path profilato; determinismo; FFI grosso (struct in → struct out).
| Criterio | AF v1 (trigger + Shapely + cascade) | C++ | Rust |
| :--- | :--- | :--- | :--- |
| Geometria | Tipi già distinti in Python; Shapely nel vendor. Un port deve **non** fondere via/pad. | Possibile (CGAL/Clipper), confine pericoloso se si “semplifica” AABB. | Stesso rischio; ownership aiuta i buffer, non la semantica PCB. |
| Memoria | HubAudio è un `.kicad_pcb` grande; il costo oggi è parse + zone Shapely, non la cascade (O(sezioni)). Nessuna misura che Python non basti. | Arena/SoA utili dopo profilo. | Stesso, dopo misura. |
| Hot path | Non profilato. Candidati *futuri* restano parser PCB e point-in-poly, non PE-AF isolato. | Solo se il profilo lo dice. | Idem. |
| Determinismo | Cascade ABCD e Z0 chiusi sono deterministici. | ok | ok (niente HashMap nel testo finding). |
| FFI grosso | Un rewrite ora = due runtime + duplicare LayoutGraph. **Complicherebbe** (Michele). | pybind/nanobind, grosso se si passa tutta la board. | PyO3, stesso costo. ImpedenceFinder resterebbe Python/Shapely. |
**Decisione:** v1 Python. Nessun pezzo scelto per C++ o Rust. Michele può volere Rust un giorno; sequenza obbligatoria resta: Python corretto → misura HubAudio → profilo → scelta esplicita. ImpedenceFinder non si riscrive “per Rust”. OpenEMS non è candidato a nessun linguaggio in Periscope.
+85
View File
@@ -0,0 +1,85 @@
# Criteri Rust — Periscope
Percorso locale: `/Users/michelebigi/Development/periscope/docs/rust-criteri.md`.
Costituzione: Python è il default. Rust **non** è un default. Questo documento dice *quando* un pezzo può entrare in Rust. Non sceglie ancora un pezzo. **Niente `rustup`, crate, né FFI finché una riga sotto non è scelta *e* misurata.**
FEM / OpenEMS / field solver: fuori dal prodotto. Non sono candidati Rust.
DRC: KiCad. Non è un candidato Rust in Periscope.
## Non solo velocità
Un bottleneck di CPU non basta. Un pezzo va in Rust solo se **tutti** i punti seguenti sono veri.
1. **Correttezza geometrica** — pad ≠ via ≠ traccia ≠ zona deve sopravvivere al confine. Se Rust collassa oggetti per “è più facile in un AABB”, il pezzo è rifiutato anche se è più veloce.
2. **Memoria / ownership** — pressione reale (PCB grandi, segmenti, zone) o lifetime che Python non può possedere senza copie cieche. Non “magari un giorno”.
3. **Parser o hot path** — il costo sta in un ciclo stretto (parse `.kicad_pcb`, walk segmenti, predicate geometriche) dopo profiling. Non nellorchestrazione, non nellI/O HTTP, non nellLLM.
4. **Determinismo** — stessa input + config → stesso modello e stessi numeri. Niente hash random, niente ordine di hash map visibile nei finding, niente dipendenza dallLLM.
5. **Confine Python grosso** — una chiamata: struct in → struct out. Vietato un round-trip per pad, per via, per “is_point_in_poly” dal loop Python.
Se manca anche uno solo di questi, il pezzo resta in Python.
## Sequenza obbligatoria (costituzione §§3336)
```text
implementazione corretta in Python
misura (wall + allocazioni, board reale: HubAudio / Emmaforo)
profiling (il hot path ha un nome di funzione)
scelta esplicita del pezzo in questo file
Rust con confine grosso
benchmark sulla stessa board
accetta / rifiuta sui numeri e sulla semantica (via resta via)
```
Finché la riga “Pezzo scelto” sotto è vuota: **nessun rustup**.
## Cosa non va in Rust
| Area | Perché |
| --- | --- |
| Pipeline, job, SSE, FastAPI | orchestrazione |
| Estrazione datasheet, skills, LLM | I/O + modello |
| Review AI, normalize, dedup | non deterministico in autorità |
| Project CRUD, storage, report JSON | I/O |
| Frontend | altro runtime |
| Auth / JWT / users | fuori perimetro; non toccare |
| FEM, OpenEMS, ampacity IPC via, DRC | non è Periscope |
| ImpedenceFinder venduto | già un core chiuso; non riscrivere “per Rust” |
| Un check `PE-*` isolato | il check è regola + evidenza; il costo è il parser/geometria a monte |
## Candidati *solo dopo misura* (nessuno scelto)
Questi sono i posti dove un profilo *potrebbe* mostrare un hot path. Non sono un piano di porting.
- Parser `.kicad_pcb` (`parsers_kicad_pcb.py`) se il wall su HubAudio è il parse, non i check.
- Predicate geometriche usate da stub / zone / courtyard (track graph, point-in-poly) se il walk segmenti domina.
- Walk grafo net→pin su BOM grandi, se misurato.
Non candidati: `run_pcb_checks` come god-object Rust; “tutto il core”; Z inventata più veloce.
## Pezzo scelto
Nessuno.
Nessuna misura registrata in questo file. Quindi: niente toolchain Rust in questa macro-fase.
## Come registrare una scelta (futuro)
Quando una misura esiste, aggiungere qui:
```text
Pezzo: <modulo / funzione>
Board: <HubAudio / Emmaforo / …>
Python wall: <s> alloc: <MB>
Hot path: <nome>
Ipotesi Rust: correttezza geometrica | memoria | parser | determinismo | confine
Benchmark dopo: <s> e test via≠pad ancora verdi
Decisione: accetta | rifiuta
```
-185
View File
@@ -1,185 +0,0 @@
# Periscope Privacy Policy
**Last updated: April 5, 2026**
This Privacy Policy explains how Faradworks, Inc. ("Faradworks," "we," "us," and "our") collects, uses, and discloses information in connection with the Periscope website (periscope.michelebigi.it), platform, and related services (the "Service").
This Privacy Policy is intended for free users and self-serve paid users. Enterprise customers typically use the Service under a separate agreement and (if applicable) a data processing agreement ("DPA"), which may include additional privacy and security terms.
## 1. Key definitions
**"Customer Content"** means any files, data, text, images, netlists, schematics, datasheets, design files, chat inputs, or other materials uploaded or submitted by you.
**"Outputs"** means analyses, checks, summaries, recommendations, or responses generated by the Service based on Customer Content.
**"Derived Data"** means technical artifacts generated solely to operate the Service, such as parsed text, indexes, embeddings, summaries, or extracted metadata.
**"Content"** refers collectively to Customer Content, Outputs, and Derived Data.
**"Personal Data"** (or "personal information") means information that identifies, relates to, describes, is reasonably capable of being associated with, or could reasonably be linked, directly or indirectly, with an individual, as defined under applicable law.
## 2. Roles: controller vs. processor (business customers)
Faradworks is the controller for Personal Data associated with operating the Service for users and prospective customers (for example account data, billing metadata, and website analytics).
If you upload Personal Data within Customer Content on behalf of a business, you may be the controller of that Personal Data and Faradworks may process it as a service provider/processor. Where required, we will make a DPA available upon request.
## 3. Information we collect
We collect only the information reasonably necessary to operate the Service.
### 3.1 Account information
- Name, email address, and organization (optional)
- Authentication identifiers (for example password hashes, session tokens, and account IDs)
- Subscription and plan metadata
### 3.2 Billing information
- Payments are processed by Stripe, a PCI-compliant third-party processor.
- Faradworks receives billing status and subscription metadata (for example plan name, renewal date, and payment status).
- We do not store payment card details.
### 3.3 Customer Content
- Engineering files (for example netlists, schematics, datasheets, and images)
- Chat inputs and related context
- Design rules and configuration preferences
### 3.4 Usage and operational data
Usage and performance telemetry (for example request timestamps, feature usage, response times, error rates, and billing/usage measurements). This data is generally operational in nature and is designed not to include the substance of your Customer Content, except as described in Section 6.3 (Support diagnostics).
### 3.5 Cookies and analytics preferences
- We use cookies and similar technologies needed for core site operations and security.
- We store an analytics preference cookie that records whether analytics tracking is granted or denied.
- When analytics is granted, we may collect site and product usage and performance telemetry through providers such as Vercel Analytics and Speed Insights.
### 3.6 Contact and enterprise inquiry data
- Contact and profile details submitted through contact or enterprise inquiry forms (for example name, email, business type, and capacity needs)
- Interest signals (for example request for a demo, free review evaluation, or higher-limit self-serve access)
- Inquiry notes and follow-up communications related to your request
## 4. How we use information
We use Personal Data and Content to:
- Provide, operate, and maintain the Service
- Perform AI-assisted engineering analysis
- Enforce usage limits and prevent abuse
- Diagnose errors and improve reliability
- Respond to support requests
- Investigate support requests and Issue Reports and, where you explicitly opt in, use those submissions and the related context to evaluate, test, debug, monitor, develop, and improve the Service
- Send service-related communications, including onboarding, feedback requests, product updates, and security notices
- Review and respond to contact or enterprise inquiries, including demo requests and plan-fit conversations
- Comply with legal obligations and enforce our Terms
## 5. AI model training and service improvement
### 5.1 No training on Customer Content for foundation models
Faradworks treats all Customer Content as confidential and does not use it to train, fine-tune, or improve any general-purpose or foundation AI models. Your content remains isolated to your account and is not shared across customers or included in public datasets.
### 5.2 Aggregated and de-identified service improvement
To improve and operate the Service, we rely primarily on aggregated or otherwise de-identified usage metrics (for example error rates and feature usage) that are not reasonably capable of being traced back to you.
## 6. How we share information
We do not sell Personal Data.
We may disclose information in the following circumstances:
### 6.1 Subprocessors and service providers
We use subprocessors and service providers to host and operate the Service (for example hosting, storage, authentication, billing, observability, and database providers). We may share Personal Data and Content with these providers only as necessary to provide the Service.
### 6.2 AI model providers
To generate Outputs, relevant portions of Customer Content are transmitted to AI model providers acting as subprocessors. Providers may include services such as DeepSeek, Anthropic, Google, or similar AI platforms.
These providers process Content to generate responses. Their data handling, retention, and caching practices are governed by their respective terms and our configuration.
### 6.3 Support and troubleshooting diagnostics
When needed for reliability, security, abuse prevention, or support troubleshooting, we may process account-linked technical diagnostics (for example request IDs, timestamps, stack traces, provider error payloads, and limited excerpts of inputs or outputs associated with a failing request).
If you submit a support request, submit an Issue Report, or otherwise ask us to investigate an issue with the Service, we may access and review the Customer Content, Outputs, and related Derived Data reasonably necessary to investigate, reproduce, resolve, remediate, and prevent recurrence of that issue. This may include the affected project, review results, uploaded files or excerpts, citations, configuration context, and associated diagnostics.
If, through the applicable in-product support or feedback flow, you explicitly opt in to broader improvement use, we may also use the submitted materials and the reasonably necessary related project/review context to evaluate, test, debug, monitor, support, secure, operate, develop, and improve the Service and related features, systems, and workflows, including for the benefit of other users. This may include quality evaluation, failure analysis, prompt and retrieval improvements, ranking or classification improvements, validation logic, reliability engineering, abuse prevention, and other product-quality, safety, and operational improvements.
We limit this access and use to authorized personnel and permitted service-related purposes. We do not use this content to train, fine-tune, or improve any general-purpose or foundation AI model unless you separately and expressly opt in to that use.
Outside of those circumstances, we do not access or review the substance of your Customer Content except: (a) at your request, (b) to investigate security issues or incidents, (c) if legally compelled, or (d) with your explicit consent.
### 6.4 Legal and safety
We may disclose information to comply with applicable law, lawful requests, and legal process; to protect the rights, property, and safety of Faradworks, our users, and others; and to enforce our agreements and policies.
### 6.5 Business transfers
If Faradworks is involved in a merger, acquisition, financing, reorganization, bankruptcy, or sale of assets, information may be transferred as part of that transaction, subject to standard confidentiality protections.
## 7. Cookies and analytics controls
You can control analytics cookies through the in-product or site controls (where available) and through your browser settings. If you deny analytics cookies, we will not run optional analytics tracking, but essential cookies may still be required for core functionality and security.
## 8. Data retention and deletion
### 8.1 User-controlled deletion
You may delete uploaded files, chats, and review history from within the Service (where available) and you may request closure of your account.
### 8.2 Retention periods
**Active accounts.** We retain Customer Content and Outputs for as long as your account remains active, unless you delete them earlier.
**Account closure.** When you close your account (or we close it at your request), we will delete Customer Content and Outputs associated with your account within 30 days, except where retention is required by law or for legitimate business purposes described below.
**Backups.** Residual metadata or encrypted backups may persist for a limited period (generally up to 90 days) for security, integrity, and disaster-recovery purposes.
**Operational artifacts.** We may retain limited technical artifacts (for example hashed identifiers, aggregated statistics, and anonymized error metadata) for security, abuse prevention, system integrity, and service improvement. These artifacts are not intended to and are not reasonably capable of reconstructing your original designs.
**Support and improvement records.** If you submit a support request or an Issue Report, we may retain the support record, related investigation notes, and the limited associated project/review context needed to document, resolve, and prevent recurrence of the issue. If you explicitly opt in to broader improvement use, we may also retain the submitted materials and related analyses for the service-improvement purposes described in this Policy, subject to the same confidentiality and deletion framework described in this Policy.
**Billing and accounting.** We retain billing records and aggregated usage statistics as required by law and for legitimate business purposes (for example taxes, accounting, and audit).
## 9. Security
We use commercially reasonable administrative, technical, and organizational safeguards designed to protect information, including encryption in transit (TLS) and at rest, per-user access isolation, secure credential management, and monitoring. No system is perfectly secure.
## 10. International data transfers
By default, the Service is hosted in the United States. If you access the Service from outside the United States, information may be transferred to, stored in, and processed in the United States and other countries where we or our subprocessors operate. Where required, we will use appropriate safeguards for international transfers (for example contractual protections in a DPA).
## 11. Your rights and choices
### 11.1 GDPR/UK GDPR
Depending on your jurisdiction, you may have rights to access, correct, delete, restrict, object to processing, and port your Personal Data. You may also have the right to withdraw consent where processing is based on consent.
### 11.2 California (CCPA/CPRA)
If you are a California resident, you may have rights to know, access, delete, correct, and opt out of the "sale" or "sharing" of Personal Data, and to limit the use of "sensitive personal information," as those terms are defined under California law. Faradworks does not sell Personal Data. We do not share Personal Data for cross-context behavioral advertising.
### 11.3 How to exercise rights
Privacy requests (data access, deletion, correction): dev@faradworks.com
For faster handling, use subject line: "Privacy Request (Access/Deletion/Correction)".
We will respond to verified privacy requests within applicable legal timelines (typically within 30 days for GDPR requests).
## 12. Children
The Service is not directed to children, and we do not knowingly collect Personal Data from children under 13 (or under the age threshold applicable in your jurisdiction).
## 13. Changes to this Privacy Policy
We may update this Privacy Policy from time to time. If we make material changes, we will provide reasonable notice by email or by posting a notice on the Service before the changes take effect. The updated policy will be effective as of the "Last updated" date unless otherwise stated.
## 14. Contact
Questions about this Privacy Policy: [dev@faradworks.com](mailto:dev@faradworks.com)
-355
View File
@@ -1,355 +0,0 @@
# Periscope Terms of Service
**Last updated: April 5, 2026**
These Terms of Service ("Terms") govern access to and use of the Periscope platform (periscope.michelebigi.it) and related services (the "Service"). These Terms apply to free users and self-serve paid users. If you have a separate written agreement signed by Faradworks, Inc. (for example, an enterprise agreement), that agreement governs your use of the Service to the extent it conflicts with these Terms.
These Terms incorporate Faradworks' [Privacy Policy](/privacy) and any policies referenced in the Service.
By creating an account, clicking to accept these Terms (for example, by clicking an "I agree" button in our signup flow), or otherwise accessing or using the Service, you agree to be bound by these Terms. If you do not agree, do not use the Service.
## 1. Definitions
**"Customer Content"** means any files, data, text, images, netlists, schematics, datasheets, design files, chat inputs, or other materials uploaded or submitted by you.
**"Outputs"** means analyses, checks, summaries, recommendations, or responses generated by the Service based on Customer Content.
**"Derived Data"** means technical artifacts generated solely to operate the Service, such as parsed text, indexes, embeddings, summaries, or extracted metadata.
**"Service"** means the Periscope platform (periscope.michelebigi.it), including all features, APIs, and related services.
**"Content"** refers collectively to Customer Content, Outputs, and Derived Data.
**"Faradworks," "we," and "us"** means Faradworks, Inc., a Delaware corporation.
## 2. Acceptance; eligibility; authority; electronic communications
### 2.1 Authority.
If you use the Service on behalf of a company or other entity, you represent and warrant that you have authority to bind that entity. In that case, "you" and "your" refer to that entity.
### 2.2 Eligibility.
You must be at least 18 years old (or the age of legal majority where you live) to use the Service.
### 2.3 Electronic delivery and notices.
You consent to receive communications from Faradworks electronically (for example, by email and in-product notices). You agree that all agreements, notices, disclosures, and other communications we provide electronically satisfy any legal requirement that such communications be in writing.
## 3. Service description; informational use; no professional advice
### 3.1 Informational service.
The Service analyzes user-submitted electrical design files and datasheets using automated systems, including machine learning models, to generate informational Outputs. Outputs are provided on an "AS IS" and "AS AVAILABLE" basis.
### 3.2 No professional engineering advice.
The Service does not provide professional engineering, safety, regulatory, certification, legal, or compliance advice. You are solely responsible for independently reviewing and validating any Outputs before use in real-world designs, fabrication, procurement, manufacturing, or deployment. Outputs may be incomplete, inaccurate, or unsuitable for your specific application.
### 3.3 AI limitations.
You acknowledge that AI-generated Outputs are probabilistic and may be inaccurate, incomplete, or misleading; that Output quality depends on input quality; and that models and Outputs may change over time.
## 4. Accounts; security; administrators
### 4.1 Account security.
You are responsible for maintaining the confidentiality of your credentials and for all activity occurring under your account. You must promptly notify Faradworks if you suspect unauthorized access.
### 4.2 Administrators and workspace users.
If your account supports multiple users, administrators may be able to manage users, permissions, billing, and settings within your workspace. You are responsible for actions taken by anyone you allow to access the Service through your account.
### 4.3 Responsibility for systems and backups.
You are responsible for your own systems, networks, and devices used to access the Service, and for maintaining appropriate backups of your Customer Content.
## 5. Ownership; licenses; feedback
### 5.1 Your ownership.
You retain all right, title, and interest in and to your Customer Content.
### 5.2 Outputs.
To the extent permitted by law, you own the Outputs generated from your Customer Content. Ownership of Outputs does not confer ownership of the Service, software, models, or analytical methods used to generate them.
### 5.3 Faradworks ownership.
Faradworks retains all right, title, and interest in and to the Service (including its software, models, workflows, analytical methods, user interfaces, and underlying infrastructure), including all improvements and derivatives.
### 5.4 License to operate the Service.
You grant Faradworks a limited, non-exclusive, worldwide, royalty-free license to host, store, process, transmit, reproduce (as necessary for processing), and otherwise use your Customer Content and Derived Data solely to provide, maintain, secure, and support the Service. Any broader use of Customer Content, Outputs, support requests, Issue Reports, or related project/review context for service-improvement purposes is permitted only to the extent expressly described in these Terms, the Privacy Policy, and any opt-in choices you make in the Service.
### 5.5 No model training on Customer Content.
Faradworks will not use Customer Content to train, fine-tune, or improve any general-purpose or foundation AI model, and will not permit third parties to do so, unless you separately and explicitly agree to that use.
### 5.6 Support reports and optional improvement consent.
By default, Faradworks will not use Customer Content, Outputs, support requests, Issue Reports, or related project/review context to improve the Service beyond investigating, resolving, and preventing recurrence of the specific incident for which such materials were submitted.
If you explicitly opt in through the applicable in-product support or feedback flow, you grant Faradworks a limited, revocable, non-exclusive, worldwide, royalty-free license to access, review, retain, and use the submitted materials and the reasonably necessary related Customer Content, Outputs, Derived Data, and project/review context to evaluate, test, debug, monitor, support, secure, operate, develop, and improve the Service and related features, systems, and workflows. This may include quality evaluation, failure analysis, prompt and retrieval improvements, ranking or classification improvements, validation logic, reliability engineering, abuse prevention, and other product-quality, safety, and operational improvements for the benefit of current and future users.
This consent does not authorize Faradworks or any third party to train, fine-tune, or improve any general-purpose or foundation AI model unless you separately and expressly agree to that use.
You may withdraw this optional improvement consent at any time through the Service settings or by contacting Faradworks. Withdrawal will apply prospectively and will not require Faradworks to unwind or delete improvements, evaluations, or analyses already created or completed before withdrawal, subject to the Privacy Policy's retention and deletion terms.
### 5.7 Feedback.
If you provide suggestions or feedback, you grant Faradworks a perpetual, irrevocable, worldwide, royalty-free license to use and incorporate it without restriction or obligation.
## 6. Customer responsibilities; prohibited data; export and restricted data
### 6.1 Rights in content you upload.
You represent and warrant that you have all rights necessary to upload and use Customer Content with the Service and to grant the rights in these Terms.
### 6.2 Prohibited Data.
Unless Faradworks expressly agrees in writing, you will not submit or upload any of the following ("Prohibited Data"): (a) patient, medical, or other protected health information regulated by HIPAA or similar laws; (b) payment card data subject to PCI DSS; (c) bank account numbers, passwords, or authentication secrets intended to access financial accounts; (d) social security numbers, driver's license numbers, or other unique government ID numbers; (e) "special categories" of personal data under the GDPR (or similar sensitive personal data classifications); or (f) any other similarly sensitive personal information that would impose heightened legal or regulatory obligations on Faradworks.
### 6.3 GDPR / DPA.
If you are subject to GDPR/UK GDPR and need a data processing agreement ("DPA"), contact us at [dev@faradworks.com](mailto:dev@faradworks.com). If we provide a DPA for your use case, you must execute it before submitting personal data governed by GDPR/UK GDPR as Customer Content. If a DPA applies, it will govern the parties' rights and obligations with respect to such personal data and will control in the event of conflict with these Terms.
### 6.4 Export-controlled and restricted technical data.
You are responsible for compliance with all applicable export control laws and regulations, including U.S. EAR and ITAR. You agree not to upload export-controlled technical data, classified information, or government-restricted information without proper authorization. By default, the Service is hosted in the United States. By using the Service, you acknowledge that Content may be processed and stored in the U.S. or other regions where we or our subprocessors operate.
## 7. Acceptable use; restrictions
You agree not to:
- (a) upload content you do not have rights to use;
- (b) upload malware, malicious code, or content intended to disrupt or compromise the Service;
- (c) circumvent usage limits or security controls;
- (d) interfere with service integrity or access others' data;
- (e) systematically extract, scrape, benchmark, or reverse engineer the Service, Outputs, or underlying models for the purpose of building a competing product;
- (f) resell, rent, or redistribute the Service without Faradworks' written consent; or
- (g) use the Service for illegal purposes or in violation of applicable laws.
Faradworks may suspend or terminate access for violations of this section.
## 8. High-risk applications
The Service is not designed or intended for use in life-critical or safety-critical systems where failure could result in death, bodily injury, or significant property or environmental damage, including medical devices, automotive safety systems, aerospace systems, nuclear facilities, or weapons systems.
If you choose to use the Service in connection with such applications, you do so at your own risk. You are solely responsible for independently validating all Outputs and for ensuring that any resulting designs, products, or systems meet all applicable safety, regulatory, and certification requirements.
## 9. Free trials; beta features; no reliance
### 9.1 Free and trial access.
Faradworks may offer free plans, free trials, promotional credits, or other no-fee access ("Free Access"). Faradworks may modify, suspend, or end Free Access at any time.
### 9.2 Beta features.
Faradworks may make available features labeled alpha, beta, preview, or similar ("Beta Features"). Beta Features are experimental and may be changed or discontinued at any time.
### 9.3 No SLA; no reliance.
Free Access and Beta Features are provided "AS IS" and "AS AVAILABLE," without any service level commitment and without any obligation to provide support. You should not rely on Free Access or Beta Features for production use.
## 10. Third-party providers; subprocessors; third-party services
### 10.1 Subprocessors.
The Service relies on third-party providers (including AI model providers, hosting, storage, authentication, billing, and observability providers) to help deliver functionality. Faradworks' data handling practices are described in the Privacy Policy.
### 10.2 Third-party services/links.
The Service may integrate with or link to third-party services. Faradworks is not responsible for third-party services, and your use of them is governed by the third party's terms and policies.
## 11. Usage limits; billing; usage allocations; taxes; refunds
### 11.1 Usage limits.
Plans may include limits on reviews, tokens, files, API spend, usage allocations, or other usage metrics. Faradworks may throttle, restrict, or suspend usage to enforce limits or protect system stability.
### 11.2 Prepaid service credits.
Certain Services, plans, or features may allow or require you to prepay for future eligible Periscope review services for professional, business, or organizational use by purchasing prepaid service credits ("Usage Credits"). Usage Credits represent a prepaid, limited, revocable, non-transferable license to access eligible Periscope review services up to the applicable credited amount and may be used only for eligible Periscope review charges as described in the Service. Faradworks may also, in its sole discretion, provide free or promotional credits ("Promotional Credits"), which may be subject to additional restrictions or expiration dates stated when issued.
### 11.3 Credit characteristics and workspace scope.
Credits may be used only for eligible Periscope review charges and may not be used for any other product or service unless Faradworks expressly states otherwise in the Service. Credits are not legal tender, are not currency, are not redeemable for cash, are not refundable except as required by law or expressly stated by Faradworks, do not constitute or confer any personal property right, and do not constitute a bank account, deposit account, stored-value account, digital wallet, payment instrument, or other monetary account. Credits are an internal service accounting mechanism that measures the amount of eligible Periscope review services you have prepaid and are licensed to use. Any credit balance or similar amount displayed in the Service reflects only our record of remaining prepaid eligibility for future eligible review charges and does not represent money held on your behalf. Credits are non-transferable, may not be sold, assigned, gifted, or sublicensed, and may be used only by the workspace or account to which they are issued. If credits are issued to an organization or workspace, they belong to that workspace and may be consumed by authorized users acting within that workspace.
### 11.4 Credit purchases and application to charges.
Your order for Usage Credits constitutes an offer to purchase those Usage Credits. Faradworks may accept or reject any purchase request in its discretion. Credits are issued when Faradworks confirms the purchase or otherwise makes the credits available in your account or workspace. Credits are applied to eligible Periscope review charges in the manner described in the Service. Faradworks may reserve, deduct, reverse, release, or adjust credits to reflect quoted charges, completed usage, failed runs, duplicate requests, fraud checks, refunds, chargebacks, or billing corrections. Credit pricing, minimum purchase amounts, maximum purchase amounts, and applicable taxes will be shown in the Service or at checkout. Fees are exclusive of taxes unless stated otherwise.
### 11.5 Credit expiration, forfeiture, and promotional credits.
Unless otherwise stated in the Service or required by law, purchased Usage Credits expire 12 months after the date they are issued to your account or workspace. Expiration does not restart because credits are partially used, because you change plans, or because your workspace or account settings change, unless Faradworks expressly states otherwise. Promotional Credits expire on the date stated when they are issued, or if no date is stated, 12 months after issuance unless required otherwise by law. Credits may be forfeited if the applicable account or workspace is closed, terminated, or suspended, subject to applicable law. Faradworks may also withhold, void, or reverse credits associated with chargebacks, payment reversals, fraud, abuse, or violations of these Terms.
### 11.6 Per-review usage impact.
Paid plans may include monthly usage limits, included usage budgets, or similar usage allocations. These allocations reset each billing period unless otherwise stated. Each review has a usage impact based on scope, selected model, and your applicable plan or pricing structure. Before you run a review, Faradworks will show the usage impact of that review, which may be displayed as a dollar amount, credit amount, percentage of plan limit, or similar usage metric. That usage impact may change over time, including for the same or a similar review configuration, and prepaid credits do not lock in a future review price unless Faradworks expressly states otherwise in the Service. Unless Faradworks expressly states otherwise, the applicable review charge is the quoted amount or usage impact shown in the Service at the time you submit or start the review, and any quote may expire or require refresh before use.
### 11.7 Plan changes.
If you change plans mid-cycle, Faradworks may apply prorated or other adjustments to your available usage limits, credits, budget, or similar usage allocation for that active billing period.
### 11.8 Auto-renewal; cancellation.
Paid subscriptions renew automatically unless canceled. You may cancel at any time through your account settings. Cancellation stops future renewals; it does not retroactively refund fees already paid except where required by law.
### 11.9 Grandfathered plans.
Grandfathered plans may remain available only while the subscription stays active and in good standing. If a grandfathered plan is canceled, lapses, or is changed, reactivation may require enrolling in a then-current plan. Faradworks may retire grandfathered plans with reasonable notice where permitted by law.
### 11.10 Taxes.
Fees are exclusive of taxes unless stated otherwise. You are responsible for applicable taxes, except taxes based on Faradworks' net income.
### 11.11 Refunds and billing corrections.
You may request a refund for completely unused Usage Credits within 24 hours after purchase by contacting [dev@faradworks.com](mailto:dev@faradworks.com). If no refund request is received within 24 hours after purchase, unused Usage Credits become non-refundable except where required by law. Once any portion of purchased Usage Credits has been used, that purchase becomes non-refundable except where required by law or expressly authorized by Faradworks. Otherwise, refunds are provided at Faradworks' discretion or as required by law. Faradworks may correct pricing errors, mistaken issuances, duplicate grants, or accounting mistakes, including by adjusting, removing, or restoring credits where appropriate.
## 12. Confidentiality; security; support access
### 12.1 Confidential Customer Content.
Faradworks treats Customer Content as confidential and does not disclose it to third parties except as necessary to provide the Service (including to subprocessors), as required by law, or with your consent, as further described in the Privacy Policy.
### 12.2 Security.
Faradworks uses commercially reasonable administrative, technical, and organizational safeguards designed to protect Content. However, no system is perfectly secure and Faradworks does not guarantee that unauthorized access, hacking, data loss, or other security incidents will never occur.
### 12.3 Security incident communications.
Where required by applicable law, Faradworks will provide notice of a confirmed unauthorized access to personal data under our control.
### 12.4 Your responsibility for sensitive material.
You are responsible for evaluating whether the Service meets your confidentiality requirements before uploading sensitive or proprietary designs.
### 12.5 Support troubleshooting access.
If you submit a support request or an Issue Report, Faradworks may access account-linked diagnostic records and the Customer Content, Outputs, and related project/review context reasonably necessary to investigate, reproduce, resolve, remediate, and prevent recurrence of the reported issue. This may include the affected project, review results, uploaded files or excerpts, citations, and associated diagnostics.
If you explicitly opt in through the applicable support or feedback flow, Faradworks may also use those submitted materials and related context for the broader service-improvement purposes described in Section 5.6. Faradworks will limit such access and use to authorized personnel and to the permitted purposes described in these Terms and the Privacy Policy.
## 13. Suspension; termination; effect of termination
### 13.1 Suspension/termination by Faradworks.
Faradworks may suspend or terminate access for: (a) violations of these Terms; (b) excessive, abusive, or fraudulent usage; (c) non-payment; (d) legal, regulatory, or infrastructure constraints; or (e) security, abuse-prevention, or risk-management reasons.
### 13.2 Termination by you.
You may stop using the Service at any time and may request account closure.
### 13.3 Effect.
Upon termination, your right to access the Service ends immediately. Faradworks will delete your Content in accordance with the Privacy Policy's data retention and deletion terms, subject to legal retention requirements and limited residual technical artifacts described in the Privacy Policy.
### 13.4 Survival.
Sections that by their nature should survive will survive termination, including ownership, confidentiality, disclaimers, limitation of liability, indemnification, disputes, and general terms.
## 14. DISCLAIMERS
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SERVICE AND OUTPUTS ARE PROVIDED "AS IS" AND "AS AVAILABLE," WITHOUT WARRANTIES OF ANY KIND, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ACCURACY, AND QUIET ENJOYMENT.
FARADWORKS DOES NOT WARRANT THAT THE SERVICE WILL BE UNINTERRUPTED, ERROR-FREE, SECURE, OR FREE OF HARMFUL COMPONENTS, OR THAT OUTPUTS WILL MEET YOUR REQUIREMENTS OR BE CORRECT FOR ANY PARTICULAR USE.
## 15. LIMITATION OF LIABILITY
### 15.1 EXCLUSION OF CERTAIN DAMAGES.
TO THE FULLEST EXTENT PERMITTED BY LAW, IN NO EVENT WILL FARADWORKS (OR ITS AFFILIATES, OFFICERS, DIRECTORS, EMPLOYEES, CONTRACTORS, AGENTS, LICENSORS, SUPPLIERS, OR SUBPROCESSORS) BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES, OR FOR ANY LOSS OF PROFITS, REVENUE, BUSINESS OPPORTUNITIES, GOODWILL, OR DATA, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
### 15.2 SPECIFIC EXCLUSIONS.
TO THE FULLEST EXTENT PERMITTED BY LAW, FARADWORKS IS NOT LIABLE FOR: (a) ERROR OR INTERRUPTION OF USE; (b) LOSS, INACCURACY, CORRUPTION, OR UNAUTHORIZED DISCLOSURE OF DATA OR CONTENT; (c) COST OF PROCUREMENT OF SUBSTITUTE GOODS, SERVICES, OR TECHNOLOGY; (d) HARDWARE FAILURES, DESIGN DEFECTS, MANUFACTURING ISSUES, OR SAFETY INCIDENTS RELATED TO DESIGNS REVIEWED USING THE SERVICE; OR (e) ANY MATTER BEYOND FARADWORKS' REASONABLE CONTROL (INCLUDING THIRD-PARTY PROVIDER FAILURES).
### 15.3 AGGREGATE CAP.
TO THE FULLEST EXTENT PERMITTED BY LAW, FARADWORKS' TOTAL AGGREGATE AND CUMULATIVE LIABILITY FOR ALL CLAIMS ARISING OUT OF OR RELATING TO THESE TERMS OR THE SERVICE, UNDER ANY THEORY OF LIABILITY (CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, STATUTE, OR OTHERWISE), WILL NOT EXCEED THE FEES PAID BY YOU TO FARADWORKS FOR THE SERVICE IN THE TWELVE (12) MONTHS PRECEDING THE FIRST EVENT GIVING RISE TO THE CLAIM. IF YOU HAVE NOT PAID ANY FEES TO FARADWORKS IN THAT PERIOD (FOR EXAMPLE, DURING FREE ACCESS OR A FREE TRIAL), FARADWORKS' TOTAL LIABILITY WILL NOT EXCEED ONE HUNDRED U.S. DOLLARS (US$100).
### 15.4 BASIS OF THE BARGAIN; FAILURE OF ESSENTIAL PURPOSE.
YOU ACKNOWLEDGE THAT THE FEES (IF ANY) REFLECT THE ALLOCATION OF RISK AND THAT FARADWORKS WOULD NOT PROVIDE THE SERVICE WITHOUT THESE LIMITATIONS. THE LIMITATIONS IN THIS SECTION APPLY EVEN IF ANY LIMITED REMEDY FAILS OF ITS ESSENTIAL PURPOSE.
### 15.5 LIMITATIONS REQUIRED BY LAW.
NOTHING IN THESE TERMS LIMITS OR EXCLUDES LIABILITY TO THE EXTENT SUCH LIMITATION OR EXCLUSION IS PROHIBITED BY APPLICABLE LAW.
## 16. Indemnification
### 16.1 Your indemnity.
You agree to indemnify, defend, and hold harmless Faradworks and its affiliates, officers, directors, employees, contractors, and agents from and against any claims, damages, losses, liabilities, and expenses (including reasonable attorneys' fees) arising out of or relating to: (a) your use of the Service or Outputs; (b) your Customer Content; (c) your violation of these Terms; (d) your violation of any third-party rights (including IP rights); or (e) designs, products, or systems you create using or informed by Outputs.
### 16.2 Indemnification procedure.
Your obligations under this Section 16 are conditioned on Faradworks: (a) providing you prompt notice of the claim (provided that failure to provide prompt notice will relieve you only to the extent materially prejudiced); (b) providing reasonable assistance at your expense; and (c) allowing you sole control of the defense and settlement of the claim, except that you may not settle any claim in a manner that admits fault by Faradworks or imposes obligations on Faradworks without Faradworks' prior written consent. Faradworks may participate in the defense with counsel of its choosing at its own expense.
## 17. Force majeure
Faradworks will not be liable for any delay or failure to perform due to events beyond its reasonable control, including acts of God, natural disasters, war, terrorism, riots, labor disputes, pandemics, public utility failures, internet or cloud provider failures, or governmental actions ("Force Majeure Events"). A Force Majeure Event does not excuse your payment obligations for fees accrued prior to the Force Majeure Event.
## 18. Disputes; governing law; venue; time limit to bring claims
### 18.1 Informal resolution.
Before filing a claim (other than for injunctive relief), you agree to first contact Faradworks at [dev@faradworks.com](mailto:dev@faradworks.com) with a brief description of the dispute and your contact information. The parties will attempt in good faith to resolve the dispute for at least 30 days.
### 18.2 Governing law.
These Terms are governed by the laws of the State of California, without regard to conflict of law principles.
### 18.3 Venue.
Any disputes arising out of or relating to these Terms or the Service must be brought in the state or federal courts located in California, and each party consents to personal jurisdiction and venue there.
### 18.4 Injunctive relief.
Nothing in these Terms prevents either party from seeking injunctive or other equitable relief to protect its intellectual property or confidential information.
### 18.5 Time limit to bring claims.
To the fullest extent permitted by law, any claim arising out of or relating to these Terms or the Service must be filed within one (1) year after the cause of action accrues; otherwise, it is permanently barred.
## 19. Changes to Terms
We may update these Terms from time to time. If we make material changes, we will provide reasonable notice by email or by posting a notice on the Service before the changes take effect. The updated Terms will be effective as of the "Last updated" date unless otherwise stated. Your continued use of the Service after the effective date, including accepting the updated Terms through the Service, constitutes acceptance of the updated Terms. If you do not agree to the changes, you must stop using the Service and close your account.
## 20. General terms
### 20.1 Entire agreement; order of precedence.
These Terms (including the [Privacy Policy](/privacy) and any policies referenced in the Service) are the entire agreement between you and Faradworks regarding the Service and supersede prior or contemporaneous agreements or understandings. If you have a separate written agreement signed by Faradworks that expressly governs the Service, that agreement will control to the extent of conflict.
### 20.2 Severability.
If any provision of these Terms is held invalid or unenforceable, the remaining provisions will remain in full force and effect.
### 20.3 Waiver.
Failure to enforce any provision is not a waiver of future enforcement.
### 20.4 Assignment.
You may not assign these Terms without Faradworks' prior written consent. Faradworks may assign these Terms in connection with a merger, acquisition, corporate reorganization, or sale of all or substantially all of its assets, or otherwise upon notice.
### 20.5 No third-party beneficiaries.
Except for Faradworks' affiliates, licensors, suppliers, and subprocessors as intended third-party beneficiaries of Sections 14 (Disclaimers) and 15 (Limitation of Liability), there are no third-party beneficiaries to these Terms.
### 20.6 Independent contractors.
The parties are independent contractors. Nothing in these Terms creates any agency, partnership, joint venture, or employment relationship.
### 20.7 Headings.
Headings are for convenience only and do not affect interpretation.
## 21. Contact
Faradworks, Inc.
Questions about these Terms or the Privacy Policy: [dev@faradworks.com](mailto:dev@faradworks.com)
-43
View File
@@ -1,43 +0,0 @@
FROM node:20-alpine AS builder
WORKDIR /app
ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ARG NEXT_PUBLIC_AUTH_MODE
ENV NEXT_PUBLIC_AUTH_MODE=$NEXT_PUBLIC_AUTH_MODE
COPY package*.json ./
RUN npm ci
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
RUN echo "BUILD API URL=$NEXT_PUBLIC_API_URL AUTH_MODE=$NEXT_PUBLIC_AUTH_MODE"
RUN npm run build
FROM node:20-alpine
WORKDIR /app
ARG NEXT_PUBLIC_API_URL
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ARG NEXT_PUBLIC_AUTH_MODE
ENV NEXT_PUBLIC_AUTH_MODE=$NEXT_PUBLIC_AUTH_MODE
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
COPY --from=builder /app/package*.json ./
RUN npm ci --omit=dev
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/src ./src
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/next.config.ts ./next.config.ts
EXPOSE 3000
CMD ["npm","run","start"]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 756 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-42
View File
@@ -1,42 +0,0 @@
/** Migrate localStorage keys from pre-rebrand `pinscopex:` prefix. */
export function migrateLocalKey(newKey: string, legacyKey: string): string | null {
if (typeof window === "undefined") return null;
try {
const current = localStorage.getItem(newKey);
if (current != null) return current;
const legacy = localStorage.getItem(legacyKey);
if (legacy != null) {
localStorage.setItem(newKey, legacy);
localStorage.removeItem(legacyKey);
return legacy;
}
} catch {
/* ignore */
}
return null;
}
export function reviewedFindingsKey(projectId: string) {
return `periscopex:reviewed-findings:${projectId}`;
}
export function legacyReviewedFindingsKey(projectId: string) {
return `pinscopex:reviewed-findings:${projectId}`;
}
export function deratingSettingsKey(projectId: string) {
return `periscopex:derating-settings:${projectId}`;
}
export function legacyDeratingSettingsKey(projectId: string) {
return `pinscopex:derating-settings:${projectId}`;
}
export function deratingOverridesKey(projectId: string) {
return `periscopex:derating-overrides:${projectId}`;
}
export function legacyDeratingOverridesKey(projectId: string) {
return `pinscopex:derating-overrides:${projectId}`;
}
+14
View File
@@ -0,0 +1,14 @@
# Periscope tree layout
Physical split (not a rewrite). AGPL `LICENSE` stays at the git root. The GitHub fork is not detached.
| Tree | Path | Role |
| --- | --- | --- |
| Native Periscope | `periscope/src/` | Finding engine clamp, PCB/placement/antenna, DeepSeek, local auth, KiCad plugin, deploy Dockerfiles |
| Inherited PinScope | `periscope/dependency/` | Graph/parsers/`validate.py`, pipeline/extraction, OSS Next.js shell, skills, taxonomy, `simple_project` |
| Third party | `vendor/impedancefinder/` | ImpedenceFinder (license UNKNOWN) |
| Glue | `backend/__init__.py` | Merges the two `backend` packages for local imports |
**Do not empty-delete `periscope/dependency/`.** Later phases replace PinScope modules incrementally in `periscope/src` (Fase C). `validate.py` stays until a native reviewer exists.
Docker overlays `dependency` then `src` into `/app`. Local frontend: `cd periscope/dependency/frontend && npm run dev` (native files are symlinked from `periscope/src/frontend`).
+149
View File
@@ -0,0 +1,149 @@
# Periscope — Agentic Schematic Validation
Periscope validates hardware schematics against component datasheets. It extracts constraints from PDFs, parses netlists and BOMs into a queryable graph, and runs an agentic validation loop to flag design violations.
> **Open-core note.** This is the open-source core. A small set of files are
> "gateway-owned seams" — pass-through stubs here (`frontend/src/proxy.ts`,
> `use-optional-auth.ts`, `clerk-theme-provider.tsx`,
> `components/billing/*`, `sidebar-auth.tsx`, `pricing-section.tsx`,
> `analytics/*`, `lib/csp-hosts.ts`) that the hosted-cloud repo replaces
> with auth/billing implementations. Keep their export signatures stable,
> and never import auth/billing SDKs anywhere else in the frontend. On the
> backend, everything reaches billing only through
> `backend/services/billing_hook.py:get_billing()` (a no-op here).
## System Overview
Three layers:
| Layer | Location | Purpose |
|-------|----------|---------|
| **Core library** | `backend/periscopex/` | Models, parsers, graph builder, agentic validator, passive resolver, taxonomy, BOM summary, derating |
| **Backend** | `backend/` | FastAPI app — async pipeline orchestration, SSE progress, project/file storage |
| **Frontend** | `frontend/` | Next.js 16 app — project dashboard, pipeline progress, report viewer, derating, admin dashboard |
Plus `skills/` — extraction prompts (pintable, patterns, specs) inlined locally for DeepSeek. Do not upload to Anthropic Console.
The pipeline stages: Parse BOM → Extract IC Pintables → Extract Simple Components → Extract Passives → DigiKey Auto-Resolve + Value Fallback → Build Graph → Direct Datasheet Review. Pipeline runs can be cancelled mid-execution via `POST /api/pipeline/{id}/cancel`.
## Example Project
`simple_project/` is the reference design for development and testing:
- **MCU**: TI MSPM0G3507SPTR (U3) — 48-pin LQFP
- **USB-UART Bridge**: CH340E (U2)
- **LDO Regulator**: SPX3819M5-L-3-3 (U1) — 5V to 3.3V
- **ESD Protection**: USBLC6-2SC6 (D1)
- **Crystal**: 8 MHz (X1) with 18pF load caps (C9, C10)
Files: `.asc` (PADS-PCB netlist; `.edn` EDIF 2.0.0 also accepted), `.csv`/`.xlsx` (BOM), `design_graph.json` (committed reference fixture used by tests).
## Architecture Principles
- **Modular extractors** — Domain-specific extraction per component type, unified constraint schema
- **Netlist as graph** — Queryable bipartite graph (components + nets) with traversal helpers
- **LLM API for PDF extraction** — Forced tool calls for structured output (pintable, passive patterns, specs). Default provider is DeepSeek.
- **Prompt caching** — Anthropic stamps `cache_control`; Gemini uses CachedContent; DeepSeek uses automatic prefix cache (cache-hit tokens in usage).
- **Local extraction skills** — `skills/*/SKILL.md` is inlined and `validate.py` runs in-process. Never call `scripts/upload_skills.py` (Anthropic Console).
- **Direct datasheet review** — The model reads the IC datasheet plus circuit neighborhood, compares to the reference application circuit, and flags issues via graph query tools (`find_connected_components`, `get_net_for_pin`, `get_pintable`). DeepSeek converts PDFs to text (and page images on the vision model).
- **Datasheet page trimming** — Large PDFs are keyword-trimmed to relevant pages before sending to Claude, reducing token cost (`pypdf`)
- **DigiKey fallback (exact MPN only)** — When pattern-based and direct extraction fail, DigiKey API fetches product parameters for auto-resolve. DigiKey matches only on exact MPN; fuzzy hits are rejected to avoid polluting the shared library with wrong-dielectric / wrong-voltage parts.
- **Value-string fallback** — When DigiKey misses an R/C/L/FB passive, a value-string resolver maps the BOM `Value` string to typed passive specs. Value-derived specs are persisted per-project only — never to the shared library.
- **Per-IC review error isolation** — Direct datasheet review runs each IC independently; one malformed payload or bad response cannot kill the whole run. Failed ICs surface as skipped components with the error.
- **Cross-IC excerpt budget (per-neighbor)** — To verify an interface finding the reviewer can pull a *connected* IC's datasheet pages (`get_datasheet_excerpt`). The budget is a global per-review page ceiling **plus a per-neighbor sub-budget**, so verifying one interface is never starved by pages already spent on other neighbors.
- **Finding normalization is downgrade-only** — A post-review per-IC normalize pass (`services/normalize_findings.py`) drops self-cancelling findings, merges same-root-cause findings, and re-grades severity — but only ever *downward*. A deterministic clamp caps each finding at the reviewer's calibrated severity (and any `Unverified:` finding at WARNING, preserving the prefix).
- **Cross-IC finding dedup** — After all per-IC reviews complete, a single pass (`services/dedupe_findings.py`) collapses one physical interface defect reported from both endpoints into a single finding. Gated by `cross_ic_dedup_enabled`; fail-soft.
- **Capacitor voltage derating** — Deterministic derating table computed from graph (ceramic/tantalum/electrolytic percentages, pass/fail per capacitor)
- **Deterministic checks over heuristics** — Exact checks where possible
- **Zero coupling between layers** — Backend calls periscopex functions with paths; frontend talks to backend via REST + SSE
- **Library deduplication** — Shared library (`library/extracted/`, `library/patterns/`, `library/models/`, `library/passives/`, `library/datasheets/`) caches extractions across projects
- **Content-addressed datasheets** — `library/datasheets/blobs/{md5}.pdf` stores unique PDFs once; `library/datasheets/refs/{safe_mpn}.json` maps MPNs to blobs (dedupe + multi-MPN sharing)
- **Taxonomy-driven extraction** — Living component taxonomy (`taxonomy/`) with per-subtype classification and specs schemas
- **Per-stage model config** — Each pipeline stage can use a different Claude model (e.g., Sonnet for review, Haiku for auto-resolve)
- **API call logging** — Every Claude API call is logged with token counts, cost, and timing per pipeline run
- **Report versioning** — Each project run is stamped with the current app version on the first `/start` transition (`ProjectMeta.periscope_version`). The version comes from `frontend/content/changelog.md`'s latest `##` heading — single source of truth — read at backend startup via `backend/_version.py`.
## Datasheet Extraction
Extracted data lives in `library/extracted/` (shared) or per-project under the storage backend. One JSON per MPN, schema in `backend/periscopex/models.py`.
Per-MPN IC extraction captures:
1. **Pintable** — Pin number + name (required), description + alt functions (optional)
2. **Package info** — Base family, package, pin count, description
3. **Component subtype** — Dotted taxonomy path (e.g., `ic.mcu`, `ic.power.ldo`)
For discrete/simple components:
4. **Specs** — Component specs (value, tolerance, package, voltage rating, etc.); parameters are filtered against taxonomy specs schemas
Extraction inlines **local skills** (`skills/*/SKILL.md` + `validate.py`) against DeepSeek. Do not use Anthropic Console Skills.
## Claude Console Skills
```
skills/
├── extract-pintable/ # Pin table + package info + taxonomy
│ ├── SKILL.md # System prompt (YAML frontmatter + markdown)
│ ├── schema.json # Tool output schema
│ └── validate.py # Validation script
├── extract-pattern/ # Passive MPN pattern
└── extract-specs/ # Component specs (discrete, connectors, crystals, etc.)
```
## Taxonomy
Living component taxonomy in `taxonomy/` — one JSON file per top-level type (ic, passive, connector, crystal, discrete, fuse, switch, test_point, transformer). Each subtype entry includes `description` and `example_mpn`.
Key taxonomy features:
- **Ref prefix mapping** — `U→ic`, `R/C/L→passive`, `D/Q→discrete`, `X→crystal`, etc.
- **Dotted subtype paths** — e.g., `ic.mcu`, `passive.capacitor.ceramic`, `ic.protection.esd`
- **Dynamic growth** — `add_subtype()` adds new entries; concurrent-safe JSON writes
- **Specs schema auto-generation** — Type-level and subtype-level parameter specs schemas are auto-generated via Claude when a taxonomy entry has none; extraction discards parameters not in the schema (`extra_specs` field)
## Scripts
- `scripts/upload_skills.py` — leftover Claude Console uploader. **Do not run.** Skills are local + DeepSeek only.
- `scripts/migrate_datasheets_to_library.py` — One-time migration: copy per-project datasheets to `library/datasheets/` (dry-run by default, `--apply` to execute)
- `scripts/migrate_datasheets_to_blobs.py` — Migrate named-PDF datasheets into the content-addressed blobs/refs layout (dry-run by default, `--apply` to execute)
- `scripts/dedup_library_datasheets.py` — Remove redundant per-MPN datasheet PDFs when a passive pattern already has a `datasheet_key` (dry-run by default, `--apply` to execute)
- `scripts/gc_orphan_blobs.py` — Garbage-collect `library/datasheets/blobs/*.pdf` not referenced by any ref file
- `scripts/clear_rules_from_extractions.py` — Strip deprecated `rules`/`absolute_maximum_ratings` from existing library extractions
## Tech Stack
- **Core**: Python 3.12+, Pydantic 2.x, OpenAI SDK (DeepSeek), Anthropic SDK (optional), google-genai (optional), openpyxl, pypdf, PyMuPDF
- **Backend**: FastAPI, uvicorn, sse-starlette, pydantic-settings
- **Frontend**: Next.js 16 (App Router, Turbopack), React 19, Tailwind CSS v4, shadcn/ui (Base UI), react-pdf
- **AI**: DeepSeek Chat Completions (OpenAI-compatible) with forced tool calls for extraction and agentic review. Do not route stages to Anthropic.
- **Model**: `deepseek-flash` for extraction, review, auto-resolve, and normalize (per-stage overrides via `.env`)
- **Skills**: Local SKILL.md + validate.py on DeepSeek
- **External APIs**: DigiKey API v4 (OAuth2) — optional datasheet auto-fetch and parameter-based auto-resolve (`DIGIKEY_CLIENT_ID`, `DIGIKEY_CLIENT_SECRET`)
## Extracted Model Versioning
All `ComponentConstraints` extracted JSON files carry a `model_version` semver field:
- **Initial value** — set from `default_model_version` in `backend/skills_manifest.json` (starts at `1.0.0`)
- **Minor bump** — increment `default_model_version` in `skills_manifest.json` when extraction prompts change (do **not** run `upload_skills.py`).
**Rule**: When committing changes under `skills/`, bump `default_model_version` locally. Never call Anthropic.
## Development Guidelines
- Write tests against `simple_project/` — it's the ground truth
- Netlist parser and BOM parser are pure functions with no side effects
- All data structures use Pydantic models in `backend/periscopex/models.py`
- Frontend types in `frontend/src/lib/types.ts` must stay in sync with `backend/periscopex/models.py`
- Extraction prompts live in `skills/` (SKILL.md + schema.json + validate.py) and run locally against DeepSeek
- **Never swallow exceptions silently** — prefer logging or re-raising over bare `except: continue`. Silent failures hide real bugs.
## Running
```bash
# Backend (copy backend/.env.example to .env at repo root first)
python3 -m uvicorn backend.main:app --reload # localhost:8000
# Frontend
cd frontend && npm run dev # localhost:3000
```
Local mode needs no cloud services and no auth — projects are stored in `data/` and you are `user_id="local"` with admin access.
+14
View File
@@ -0,0 +1,14 @@
"""PinScope-inherited backend package (in-tree dependency)."""
from pkgutil import extend_path
__path__ = list(extend_path(__path__, __name__))
_src, _other, _dep = [], [], []
for _p in __path__:
_n = str(_p).replace("\\", "/")
if "/periscope/src/" in _n:
_src.append(_p)
elif "/periscope/dependency/" in _n:
_dep.append(_p)
else:
_other.append(_p)
__path__[:] = _src + _other + _dep
@@ -7,6 +7,11 @@ from pathlib import Path
from pydantic import Field
from pydantic_settings import BaseSettings
from backend.repo_paths import data_dir as _data_dir
from backend.repo_paths import env_file as _env_file
from backend.repo_paths import skills_dir as _skills_dir
from backend.repo_paths import taxonomy_dir as _taxonomy_dir
# Resolve paths relative to the project root (one level up from backend/)
_BACKEND_DIR = Path(__file__).resolve().parent
_PROJECT_ROOT = _BACKEND_DIR.parent
@@ -111,10 +116,10 @@ class Settings(BaseSettings):
# single finding. Runs once after all per-IC reviews complete.
cross_ic_dedup_enabled: bool = True
# Paths (relative to project root, used by LocalStorageBackend)
data_dir: Path = _PROJECT_ROOT / "data"
taxonomy_dir: Path = _PROJECT_ROOT / "taxonomy"
skills_dir: Path = _PROJECT_ROOT / "skills"
# Paths (git split: data at repo root; taxonomy/skills under periscope/dependency)
data_dir: Path = _data_dir()
taxonomy_dir: Path = _taxonomy_dir()
skills_dir: Path = _skills_dir()
# GCS (if set, use GCSStorageBackend; otherwise LocalStorageBackend)
gcs_bucket: str = ""
@@ -193,7 +198,7 @@ class Settings(BaseSettings):
pipeline_sweeper_stale_seconds: int = 60
model_config = {
"env_file": str(_BACKEND_DIR / ".env"),
"env_file": str(_env_file()),
"env_file_encoding": "utf-8",
"extra": "ignore",
}
@@ -0,0 +1,13 @@
from pkgutil import extend_path
__path__ = list(extend_path(__path__, __name__))
_src, _other, _dep = [], [], []
for _p in __path__:
_n = str(_p).replace("\\", "/")
if "/periscope/src/" in _n:
_src.append(_p)
elif "/periscope/dependency/" in _n:
_dep.append(_p)
else:
_other.append(_p)
__path__[:] = _src + _other + _dep
@@ -95,6 +95,18 @@ def _dielectric_category(component_subtype: str | None, dielectric: str | None)
return "ceramic"
def _stress(op: float | None, rated: float | None) -> str:
"""PASS / MARGIN / RISK from Vop vs Vrated. No invented dielectric %."""
if op is None or rated is None or rated <= 0:
return "UNKNOWN"
ratio = op / rated
if ratio > 1.0:
return "RISK"
if ratio > 0.8:
return "MARGIN"
return "PASS"
def build_derating_table(graph: DesignGraph) -> list[dict]:
"""Build a capacitor voltage derating table from the design graph.
@@ -180,6 +192,7 @@ def build_derating_table(graph: DesignGraph) -> list[dict]:
"c_eff_f": c_eff,
"c_eff_formatted": c_eff_fmt,
"dc_bias_model": "stima" if factor is not None else None,
"stress": _stress(op_voltage, rated_v),
})
rows.sort(key=lambda r: natural_sort_key(r["designator"]))
@@ -158,9 +158,9 @@ class InductorSpecs(BaseModel):
@model_validator(mode="after")
def _require_primary_value(self) -> InductorSpecs:
if self.component_subtype == "passive.ferrite_bead":
if self.impedance_ohm is None:
raise ValueError("ferrite bead requires impedance_ohm")
return self
from backend.periscopex.ferrite_z import recover_bead_specs
return recover_bead_specs(self)
if self.value_henries is None:
raise ValueError("inductor requires value_henries")
return self
@@ -356,6 +356,19 @@ class Finding(BaseModel):
cad_sheet: str | None = None # schematic sheet filename for plugin sync
cad_uuid: str | None = None # KiCad symbol/pin uuid
variant: str | None = None # DNP / ECO / assembly variant
# Finding engine (docs/motore-finding.md) — optional for legacy JSON.
facts: str = ""
requirement: str = ""
inference: str = ""
provenance: Literal["MANDATORY", "RECOMMENDED", "TYPICAL", "EXAMPLE"] | None = None
finding_class: Literal["RULE", "RISK", "REVIEW", "INFO"] | None = None
confidence: float | None = None
evidence_status: Literal["SUFFICIENT", "INSUFFICIENT"] | None = None
calculation: str = ""
assumptions: list[str] = []
action: str = ""
decision_id: str | None = None
suppressed: bool = False
class ValidationReport(BaseModel):
@@ -367,6 +380,7 @@ class ValidationReport(BaseModel):
coverage: dict[str, list[str]] = {} # designator -> areas checked and found OK
review_errors: dict[str, str] = {} # designator -> error message for ICs whose review raised
not_reviewed: list[dict] = [] # [{"designator","reason"}] — ICs skipped (e.g. no datasheet PDF)
protocol_certification: dict[str, Any] | None = None
class FindingComment(BaseModel):
@@ -453,6 +467,7 @@ class LayoutPad(BaseModel):
x: float
y: float
net: str = ""
pinfunction: str = ""
class LayoutFootprint(BaseModel):
@@ -478,6 +493,7 @@ class LayoutVia(BaseModel):
y: float
net: str = ""
drill: float | None = None
layers: tuple[str, ...] = ()
class LayoutDielectric(BaseModel):
@@ -496,6 +512,8 @@ class LayoutZone(BaseModel):
net: str
layer: str
outlines: list[list[tuple[float, float]]] = []
keepout: bool = False
name: str = ""
class LayoutGraph(BaseModel):
@@ -306,25 +306,30 @@ def simple_to_typed_passive_specs(simple: SimpleComponentSpecs) -> ComponentSpec
if subtype == "passive.ferrite_bead":
raw = vals.get("impedance_ohm") or vals.get("value_ohms")
if raw is None:
raise ValueError("Missing impedance_ohm in auto-resolved ferrite bead specs")
impedance_ohm = None
if raw is not None:
impedance_ohm = _parse_spice_value(str(raw)) if isinstance(raw, str) else float(raw)
current_rating_a = str(vals.get("current_rating_a")) if vals.get("current_rating_a") else None
dcr_raw = vals.get("dcr_ohms")
dcr_ohms: float | None = None
if dcr_raw is not None:
dcr_ohms = _parse_spice_value(str(dcr_raw)) if isinstance(dcr_raw, str) else float(dcr_raw)
formatted = value_formatted or _format_value(impedance_ohm, "ohm")
return InductorSpecs(
formatted = value_formatted
if not formatted and impedance_ohm is not None:
formatted = _format_value(impedance_ohm, "ohm")
spec = InductorSpecs(
component_subtype=subtype_for_specs,
value_henries=None,
value_formatted=formatted,
value_formatted=formatted or "FB",
tolerance=tolerance,
package=package,
current_rating_a=current_rating_a,
dcr_ohms=dcr_ohms,
impedance_ohm=impedance_ohm,
)
from backend.periscopex.ferrite_z import recover_bead_specs
extra = " ".join(str(v) for v in vals.values() if v is not None)
return recover_bead_specs(spec, extra_text=extra)
if subtype.startswith("passive.inductor"):
raw = vals.get("value_henries")
@@ -20,6 +20,7 @@ from dotenv import load_dotenv
load_dotenv()
from backend.periscopex.finding_engine import complete_findings
from backend.periscopex.models import (
ComponentConstraints,
ComponentType,
@@ -149,6 +150,12 @@ neighbor's datasheet that you fetched via `get_datasheet_excerpt` — this \
links the page number to the right datasheet.
- **recommendation**: What to change (for ERROR/WARNING only).
This is a **design review**, not a design rule. Put observations in \
`finding` (FACT), datasheet text in `why` (REQUIREMENT), and judgment \
only there do not invent millimetres, IEC numbers, or typical values. \
Recommended datasheet notes are never ERROR. If evidence is missing, say \
so (Unverified) instead of guessing.
### Calibration
ERROR only for clear violations: required pin floating, voltage exceeding \
absolute max, required external component completely missing, wrong \
@@ -917,17 +924,26 @@ def _parse_review(
why = (
"Unverified: no verbatim datasheet quote. " + why
).strip()
rec = str(item.get("recommendation") or item.get("action") or "").strip()
act = str(item.get("action") or rec).strip()
findings.append(Finding(
designator=ic_ref,
mpn=mpn,
source_designator=src_designator,
finding=item["finding"],
facts=str(item.get("finding") or ""),
requirement=why,
inference=str(item.get("inference") or ""),
why=why,
status=status,
source_page=page,
source_quote=item.get("source_quote", ""),
recommendation=item.get("recommendation", ""),
recommendation=rec,
action=act,
reference=f"{src_mpn} datasheet p.{page if page is not None else '?'}",
source="review",
finding_class="REVIEW",
evidence_status="SUFFICIENT" if quote else "INSUFFICIENT",
))
except (KeyError, TypeError, ValueError) as exc:
print(f"Skipping malformed finding for {ic_ref}: {exc}", file=sys.stderr)
@@ -937,11 +953,12 @@ def _parse_review(
def assign_finding_ids(findings: list[Finding]) -> None:
"""Assign finding_id: {designator}-{001}, {002}, ..."""
"""Assign finding_id: {designator}-{001}, {002}, ... then run the finding engine."""
counter: Counter[str] = Counter()
for f in findings:
counter[f.designator] += 1
f.finding_id = f"{f.designator}-{counter[f.designator]:03d}"
complete_findings(findings)
# ---------------------------------------------------------------------------
@@ -797,7 +797,17 @@ SUBMIT_REVIEW_SCHEMA = {
},
"recommendation": {
"type": "string",
"description": "What to change to fix the issue. Only for ERROR/WARNING.",
"description": (
"What to change on the board or schematic. "
"Required for every finding, including INFO."
),
},
"action": {
"type": "string",
"description": (
"Same as recommendation if you prefer that name. "
"Required for every finding when recommendation is empty."
),
},
},
"required": ["finding", "why", "status", "source_page"],
@@ -104,8 +104,13 @@ async def _run() -> None:
elif mode == "placement":
from backend.services import placement_pipeline as placement_svc
await placement_svc.run_placement_pipeline(storage, user_id, project_id)
elif mode == "pcb":
from backend.services import pcb_pipeline as pcb_svc
await pcb_svc.run_pcb_pipeline(storage, user_id, project_id)
else:
raise SystemExit(f"unknown MODE={mode!r}; expected 'run', 'regen', or 'placement'")
raise SystemExit(
f"unknown MODE={mode!r}; expected 'run', 'regen', 'placement', or 'pcb'"
)
def main() -> None:
@@ -0,0 +1,3 @@
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
@@ -463,7 +463,7 @@ async def events(project_id: str, request: Request):
break
ev = msg["event"]
# Skip placement events in the shared log.
if ev.startswith("placement_"):
if ev.startswith("placement_") or ev.startswith("pcb_"):
continue
yield {
"event": ev,
@@ -527,6 +527,9 @@ async def status(project_id: str, request: Request):
"placement_status": meta.placement_status,
"placement_state": meta.placement_state,
"placement_running": (meta.placement_status or "draft") in ("queued", "running"),
"pcb_status": meta.pcb_status,
"pcb_state": meta.pcb_state,
"pcb_running": (meta.pcb_status or "draft") in ("queued", "running"),
"healed": healed is not None,
}
@@ -548,6 +551,7 @@ _PLACEMENT_SSE_TERMINAL = frozenset({
async def start_placement(project_id: str, request: Request):
"""Enqueue the Placement topology pipeline (free, no analysis status change)."""
from backend.services.placement_pipeline import analysis_busy, placement_busy
from backend.services.pcb_pipeline import pcb_busy
storage = get_storage(request)
owner_user_id, meta = await resolve_or_404(request, project_id)
@@ -557,6 +561,8 @@ async def start_placement(project_id: str, request: Request):
raise HTTPException(409, "Analysis pipeline is running; wait or cancel it first")
if placement_busy(meta):
raise HTTPException(409, "Placement pipeline already running or queued")
if pcb_busy(meta):
raise HTTPException(409, "PCB review is running; wait or cancel it first")
if (meta.placement_status or "draft") not in _PLACEMENT_START_OK:
raise HTTPException(
409,
@@ -694,7 +700,7 @@ async def placement_events(project_id: str, request: Request):
if not (
ev.startswith("placement_")
or ev == "heartbeat"
):
) or ev.startswith("pcb_"):
continue
yield {
"event": ev,
@@ -734,6 +740,187 @@ async def placement_events(project_id: str, request: Request):
)
# ---------------------------------------------------------------------------
# PCB review pipeline (parallel — exam, not auto-place)
# ---------------------------------------------------------------------------
_PCB_START_OK = frozenset({"draft", "complete", "error", "cancelled"})
_PCB_SSE_TERMINAL = frozenset({
"pcb_complete",
"pcb_error",
"pcb_cancelled",
})
@router.post("/pipeline/{project_id}/pcb/start", status_code=202)
async def start_pcb(project_id: str, request: Request):
from backend.services.pcb_pipeline import analysis_busy, pcb_busy, placement_busy
storage = get_storage(request)
owner_user_id, meta = await resolve_or_404(request, project_id)
if not meta.has_pcb:
raise HTTPException(400, "Upload a .kicad_pcb before starting PCB review")
if not meta.has_bom or not meta.has_netlist:
raise HTTPException(400, "Upload BOM and netlist before starting PCB review")
if analysis_busy(meta):
raise HTTPException(409, "Analysis pipeline is running; wait or cancel it first")
if placement_busy(meta):
raise HTTPException(409, "Placement pipeline is running; wait or cancel it first")
if pcb_busy(meta):
raise HTTPException(409, "PCB review already running or queued")
if (meta.pcb_status or "draft") not in _PCB_START_OK:
raise HTTPException(
409,
f"Cannot start PCB review from pcb_status={meta.pcb_status}",
)
proj_svc.update_project(
storage, owner_user_id, project_id,
pcb_status="queued",
pcb_cancel_requested=False,
pcb_state=None,
pcb_execution_name=None,
)
try:
event_bridge.GCSEventBroker(storage, owner_user_id).clear_history(project_id)
except Exception:
logger.exception("failed to clear events before PCB start for %s", project_id)
try:
execution_name = job_runner.enqueue_pcb_pipeline(
project_id, owner_user_id,
)
except Exception:
logger.exception("enqueue_pcb_pipeline failed for %s", project_id)
proj_svc.update_project(
storage, owner_user_id, project_id,
pcb_status="error",
pcb_state={"error": "Failed to enqueue PCB worker"},
)
raise HTTPException(503, "Failed to enqueue PCB worker; please retry")
proj_svc.update_project(
storage, owner_user_id, project_id,
pcb_execution_name=execution_name,
)
return {"status": "started", "project_id": project_id}
@router.post("/pipeline/{project_id}/pcb/cancel")
async def cancel_pcb(project_id: str, request: Request):
from backend.services.pcb_pipeline import pcb_busy
storage = get_storage(request)
owner_user_id, meta = await resolve_or_404(request, project_id)
if not pcb_busy(meta):
raise HTTPException(
409,
f"PCB review is not running (pcb_status={meta.pcb_status})",
)
proj_svc.update_project(
storage, owner_user_id, project_id,
pcb_cancel_requested=True,
)
return {"status": "cancel_requested", "project_id": project_id}
@router.get("/pipeline/{project_id}/pcb/inventory")
async def get_pcb_inventory(project_id: str, request: Request):
storage = get_storage(request)
owner_user_id, _ = await resolve_or_404(request, project_id)
key = f"{proj_svc.project_prefix(owner_user_id, project_id)}/pcb_inventory.json"
if not storage.exists(key):
raise HTTPException(404, "PCB inventory not found — run PCB review first")
return storage.read_json(key)
@router.get("/pipeline/{project_id}/pcb/events")
async def pcb_events(project_id: str, request: Request):
owner_user_id, meta = await resolve_or_404(request, project_id)
storage = get_storage(request)
async def event_generator():
execution_name = meta.pcb_execution_name
crash_detected: dict[str, str | None] = {"reason": None}
async def watch_status() -> None:
poll_interval = 2.0
saw_active = (meta.pcb_status or "draft") in ("queued", "running")
while True:
await asyncio.sleep(poll_interval)
try:
cur = proj_svc.get_project(storage, owner_user_id, project_id)
except Exception:
continue
if cur is None:
continue
pst = cur.pcb_status or "draft"
if pst in ("queued", "running"):
saw_active = True
elif saw_active and pst in ("complete", "error", "cancelled"):
crash_detected["reason"] = f"pcb_status={pst} (terminal)"
return
if execution_name:
try:
state = job_runner.get_execution_state(execution_name)
except Exception:
state = "unknown"
if state in _EXEC_TERMINAL and (
saw_active or pst in ("queued", "running")
):
crash_detected["reason"] = f"execution state={state}"
return
watcher = asyncio.create_task(watch_status())
try:
async for msg in event_bridge.tail_events(
storage, owner_user_id, project_id,
terminal_events=_PCB_SSE_TERMINAL,
):
if crash_detected["reason"] is not None:
break
ev = msg["event"]
if not (ev.startswith("pcb_") or ev == "heartbeat"):
continue
yield {
"event": ev,
"data": json.dumps(msg.get("data", {})),
}
if ev in _PCB_SSE_TERMINAL:
return
if crash_detected["reason"] is not None:
cur = proj_svc.get_project(storage, owner_user_id, project_id)
from backend.services.pcb_pipeline import pcb_sse_terminal_from_status
ev, payload = pcb_sse_terminal_from_status(
cur.pcb_status if cur else None,
cur.pcb_state if cur else None,
crash_detected["reason"],
)
yield {
"event": ev,
"data": json.dumps(payload),
}
finally:
watcher.cancel()
try:
await watcher
except (asyncio.CancelledError, Exception):
pass
return EventSourceResponse(
event_generator(),
ping=15,
headers={
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
"Connection": "keep-alive",
},
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -148,6 +148,9 @@ async def get_project(project_id: str, request: Request):
healed_pl = proj_svc.heal_if_placement_stuck(storage, owner_user_id, project_id)
if healed_pl is not None:
meta = healed_pl
healed_pcb = proj_svc.heal_if_pcb_stuck(storage, owner_user_id, project_id)
if healed_pcb is not None:
meta = healed_pcb
return meta.model_dump()
@@ -903,7 +906,7 @@ async def auto_resolve(req: AutoResolveRequest, request: Request):
import asyncio
from backend.services.digikey import fetch_params
from backend.services.extraction import CatalogResolveMiss, auto_resolve_specs
from backend.services.datasheet_extract import CatalogResolveMiss, auto_resolve_specs
if not settings.use_digikey:
raise HTTPException(400, "DigiKey API not configured")
@@ -993,7 +996,7 @@ async def lcsc_resolve_passive(
from backend.services.api_logs import ApiLogger
from backend.services.billing_hook import InsufficientCredits, get_billing
from backend.services.extraction import auto_resolve_specs
from backend.services.datasheet_extract import auto_resolve_specs
storage = get_storage(request)
result = proj_svc.resolve_project_access(storage, get_user_id(request), project_id)
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
import logging
import re
import uuid
from datetime import datetime, timezone
@@ -11,6 +12,13 @@ from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse, Response
from pydantic import BaseModel
from backend.periscopex.finding_engine import (
apply_decisions,
complete_findings,
decision_from_review,
sort_findings,
upsert_decision,
)
from backend.periscopex.models import Finding
from backend.periscopex.review_workflow import (
ReviewError,
@@ -24,6 +32,7 @@ from backend.routers.deps import get_storage, get_user_id, resolve_or_404
from backend.services import projects as proj_svc
router = APIRouter(tags=["reports"])
log = logging.getLogger(__name__)
# Allow alphanumeric, dash, underscore, dot, colon, forward-slash, plus, hash, space
_SAFE_MPN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_\-\.:/ +#,()]*$")
@@ -40,10 +49,34 @@ async def get_report(project_id: str, request: Request):
storage = get_storage(request)
owner_user_id, _ = await resolve_or_404(request, project_id)
prefix = proj_svc.project_prefix(owner_user_id, project_id)
key = f"{prefix}/report.json"
if not storage.exists(key):
schema_key = f"{prefix}/report.json"
pcb_key = f"{prefix}/pcb_report.json"
schema = storage.read_json(schema_key) if storage.exists(schema_key) else None
pcb = storage.read_json(pcb_key) if storage.exists(pcb_key) else None
from backend.periscopex.pcb_checks import merge_schema_pcb_reports
merged = merge_schema_pcb_reports(schema, pcb)
if merged is None:
raise HTTPException(404, "Report not found — run the pipeline first")
return JSONResponse(storage.read_json(key))
findings = _findings_from_report(merged)
try:
complete_findings(findings)
except Exception:
log.exception("complete_findings failed while serving report %s", project_id)
sort_findings(findings)
dec_key = f"{prefix}/decisions.json"
if storage.exists(dec_key):
try:
apply_decisions(findings, storage.read_json(dec_key) or [])
except Exception:
pass
merged["findings"] = [json.loads(f.model_dump_json()) for f in findings]
summary = {"ERROR": 0, "WARNING": 0, "INFO": 0, "total": len(findings)}
for f in findings:
if f.status in summary:
summary[f.status] += 1
merged["summary"] = summary
return JSONResponse(merged)
@router.get("/report/{project_id}/cad-bridge")
@@ -132,7 +165,7 @@ def _findings_from_report(report_data: dict) -> list[Finding]:
try:
out.append(Finding.model_validate(raw))
except Exception:
continue
log.warning("Skipping malformed finding in report", exc_info=True)
return out
@@ -142,7 +175,17 @@ async def put_finding_review(project_id: str, finding_id: str, body: ReviewBody,
owner_user_id, _ = await resolve_or_404(request, project_id)
user_id = get_user_id(request)
key, report_data = _load_report(storage, owner_user_id, project_id)
ids = {f.finding_id for f in _findings_from_report(report_data) if f.finding_id}
prefix = proj_svc.project_prefix(owner_user_id, project_id)
findings = _findings_from_report(report_data)
ids = {f.finding_id for f in findings if f.finding_id}
if finding_id not in ids:
pcb_key = f"{prefix}/pcb_report.json"
if storage.exists(pcb_key):
pcb_data = storage.read_json(pcb_key)
pcb_findings = _findings_from_report(pcb_data)
if finding_id in {f.finding_id for f in pcb_findings if f.finding_id}:
key, report_data, findings = pcb_key, pcb_data, pcb_findings
ids = {f.finding_id for f in findings if f.finding_id}
if finding_id not in ids:
raise HTTPException(404, "Finding not found")
try:
@@ -158,6 +201,22 @@ async def put_finding_review(project_id: str, finding_id: str, body: ReviewBody,
raise HTTPException(400, str(exc)) from exc
report_data["review_states"] = states
storage.write_json(key, report_data)
if body.state in {"wontfix", "false_positive"}:
found = next(
(f for f in _findings_from_report(report_data) if f.finding_id == finding_id),
None,
)
if found is not None:
dec = decision_from_review(
found, state=body.state, reason=body.reason, user_id=user_id,
)
if dec is not None:
prefix = proj_svc.project_prefix(owner_user_id, project_id)
dkey = f"{prefix}/decisions.json"
existing = storage.read_json(dkey) if storage.exists(dkey) else []
if not isinstance(existing, list):
existing = []
storage.write_json(dkey, upsert_decision(existing, dec))
return JSONResponse(states.get(finding_id) or {"state": "open", "reason": ""})
@@ -0,0 +1,3 @@
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
@@ -49,6 +49,9 @@ TERMINAL_EVENTS = frozenset({
"placement_complete",
"placement_error",
"placement_cancelled",
"pcb_complete",
"pcb_error",
"pcb_cancelled",
})
@@ -1,11 +1,12 @@
"""Async datasheet extraction using the configured LLM provider.
"""Inherited PinScope datasheet extraction (fallback, not the live pipeline).
Live path since 2.40.0: ``backend.services.datasheet_extract``. This file
stays in periscope/dependency/ do not empty-delete it.
Ports the extraction steps from run_pipeline.py to async:
- extract_pintable: Pin table + package info + taxonomy assignment
- extract_pattern: Passive MPN pattern
- extract_specs: Component specs (discrete, connectors, crystals, etc.)
Skills (SKILL.md + validate.py) run locally against DeepSeek. Do not use Anthropic Console Skills.
"""
from __future__ import annotations
@@ -137,10 +138,16 @@ PINTABLE_TOOL = {
"type": "array",
"description": (
"PCB layout constraints from typical-application / PCB layout pages. "
"kind: decoupling_proximity | thermal_via | keepout | length_match. "
"kind: decoupling_proximity | thermal_via | keepout | length_match | "
"impedance | max_length | spacing | ref_plane | si_via | layer | "
"series_resistor | return_path | si | emi | common_mode | shield. "
"Fields: pin, cap_value_hint, max_distance_mm (ONLY if the PDF states a "
"number — never invent 3 mm/JEDEC), same_layer (bool), min_via_count, "
"net_class, note, source_page. Empty array if the PDF has no layout guidance."
"max_via_count, z0_ohm, zdiff_ohm, tolerance_pct, z_min_ohm, z_max_ohm, "
"topology, min_spacing_mm, value_ohms, ref_plane, parameter, "
"net_class (required for SI kinds: usb2 | usb3 | eth_mdi | rgmii | "
"sgmii | ddr3 | hdmi | pcie | lvds — never map EN/CHIP_PU RC onto "
"USB), note, source_page. Empty array if the PDF has no layout guidance."
),
"items": {
"type": "object",
@@ -152,6 +159,18 @@ PINTABLE_TOOL = {
"thermal_via",
"keepout",
"length_match",
"impedance",
"max_length",
"spacing",
"ref_plane",
"si_via",
"layer",
"series_resistor",
"return_path",
"si",
"emi",
"common_mode",
"shield",
],
},
"pin": {"type": ["string", "null"]},
@@ -159,9 +178,20 @@ PINTABLE_TOOL = {
"max_distance_mm": {"type": ["number", "null"]},
"same_layer": {"type": ["boolean", "null"]},
"min_via_count": {"type": ["integer", "null"]},
"max_via_count": {"type": ["integer", "null"]},
"net_class": {"type": ["string", "null"]},
"note": {"type": ["string", "null"]},
"source_page": {"type": ["integer", "null"]},
"z0_ohm": {"type": ["number", "null"]},
"zdiff_ohm": {"type": ["number", "null"]},
"tolerance_pct": {"type": ["number", "null"]},
"z_min_ohm": {"type": ["number", "null"]},
"z_max_ohm": {"type": ["number", "null"]},
"topology": {"type": ["string", "null"]},
"min_spacing_mm": {"type": ["number", "null"]},
"value_ohms": {"type": ["number", "null"]},
"ref_plane": {"type": ["string", "null"]},
"parameter": {"type": ["string", "null"]},
},
"required": ["kind"],
},
@@ -350,6 +350,9 @@ def get_execution_state(execution_name: str | None) -> ExecutionState:
if execution_name.startswith("local/placement/"):
project_id = execution_name.split("/", 2)[-1]
return _local_state(f"placement:{project_id}")
if execution_name.startswith("local/pcb/"):
project_id = execution_name.split("/", 2)[-1]
return _local_state(f"pcb:{project_id}")
return _cloud_run_state(execution_name)
@@ -369,6 +372,10 @@ def cancel_execution(execution_name: str | None) -> None:
project_id = execution_name.split("/", 2)[-1]
_local_cancel(f"placement:{project_id}")
return
if execution_name.startswith("local/pcb/"):
project_id = execution_name.split("/", 2)[-1]
_local_cancel(f"pcb:{project_id}")
return
_cloud_run_cancel(execution_name)
@@ -383,3 +390,16 @@ def enqueue_placement_pipeline(project_id: str, user_id: str) -> str:
proc_key=f"placement:{project_id}",
execution_name=f"local/placement/{project_id}",
)
def enqueue_pcb_pipeline(project_id: str, user_id: str) -> str:
"""Dispatch the parallel PCB review pipeline (deterministic + AI exam)."""
if use_cloud_run_jobs():
return _enqueue_cloud_run_job(
project_id, user_id, resume=False, free=False, mode="pcb",
)
return _spawn_local_subprocess(
project_id, user_id, resume=False, free=False, mode="pcb",
proc_key=f"pcb:{project_id}",
execution_name=f"local/pcb/{project_id}",
)
@@ -5,6 +5,9 @@ All model calls in the backend route through this package via the
overrides via ``Settings.provider_*`` env vars route specific stages to
Anthropic or Gemini if those keys are configured.
"""
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from backend.services.llm.factory import call_with_fallback, get_provider
from backend.services.llm.types import (
@@ -47,7 +47,7 @@ from backend.config import settings
from backend.services import admin_settings as settings_svc
from backend.services.billing_hook import InsufficientCredits, get_billing
from backend.services.datasheet_store import compute_md5_from_path, store_datasheet, store_datasheet_bytes
from backend.services import extraction, projects as proj_svc
from backend.services import datasheet_extract as extraction, projects as proj_svc
from backend.services.api_logs import ApiLogger, total_cost
from backend.services.cost_estimator import estimate_stage_cost_usd
from backend.services.storage import StorageBackend
@@ -95,58 +95,20 @@ def _git_commit() -> str:
# ---------------------------------------------------------------------------
# SSE Event Broker
# ---------------------------------------------------------------------------
# SSE Event Broker + workspace live in periscope/src job_workspace.py.
# Re-export so analysis run_pipeline and pipeline_worker.set_broker stay
# on one singleton. PinScope pipeline.py is not empty-deleted.
from backend.services import job_workspace as _job_ws
class EventBroker:
"""In-memory pub/sub for SSE events, keyed by project_id.
Buffers all events per project so late subscribers (e.g. after a page
navigation) receive the full history before seeing live events.
"""
def __init__(self):
self._queues: dict[str, list[asyncio.Queue]] = {}
self._history: dict[str, list[dict]] = {}
def subscribe(self, project_id: str) -> asyncio.Queue:
q: asyncio.Queue = asyncio.Queue()
# Replay buffered events so the subscriber catches up
for msg in self._history.get(project_id, []):
q.put_nowait(msg)
self._queues.setdefault(project_id, []).append(q)
return q
def unsubscribe(self, project_id: str, q: asyncio.Queue) -> None:
qs = self._queues.get(project_id, [])
if q in qs:
qs.remove(q)
if not qs:
self._queues.pop(project_id, None)
def clear_history(self, project_id: str) -> None:
self._history.pop(project_id, None)
def publish(self, project_id: str, event: str, data: dict) -> None:
msg = {"event": event, "data": data}
self._history.setdefault(project_id, []).append(msg)
for q in self._queues.get(project_id, []):
q.put_nowait(msg)
EventBroker = _job_ws.EventBroker
PipelineWorkspace = _job_ws.PipelineWorkspace
broker = _job_ws.broker
broker: EventBroker = EventBroker()
def set_broker(b: EventBroker) -> None:
"""Replace the module-level broker.
Called by :mod:`backend.pipeline_worker` at startup to swap in the
GCS-backed broker so events written from the worker are visible to
the API's SSE handler. Must be called *before* :func:`run_pipeline`
or :func:`run_regen_pipeline`.
"""
global broker
broker = b
def set_broker(b) -> None:
"""Swap the worker event broker (GCS in prod). Updates native + this module."""
_job_ws.set_broker(b)
globals()["broker"] = b
# Per-process cancel-flag cache: re-reading the project meta from GCS on
@@ -189,158 +151,6 @@ def _cancel_gate_check(ctx: PipelineContext) -> None:
raise CancelRequested(f"cancel requested for {ctx.project_id}")
# ---------------------------------------------------------------------------
# Pipeline Workspace
# ---------------------------------------------------------------------------
class PipelineWorkspace:
"""Downloads project files from storage to a temp dir for pipeline execution.
The periscopex core library operates on local paths. This context manager
downloads inputs at enter, provides local paths, and uploads results at exit.
"""
def __init__(
self,
storage: StorageBackend,
user_id: str,
project_id: str,
) -> None:
self.storage = storage
self.user_id = user_id
self.project_id = project_id
self.prefix = proj_svc.project_prefix(user_id, project_id)
self._tmpdir: tempfile.TemporaryDirectory | None = None
self.local_dir: Path = Path()
async def __aenter__(self) -> PipelineWorkspace:
self._tmpdir = tempfile.TemporaryDirectory()
self.local_dir = Path(self._tmpdir.name)
# Create subdirectories
(self.local_dir / "uploads" / "datasheets").mkdir(parents=True)
(self.local_dir / "extracted").mkdir(parents=True)
(self.local_dir / "patterns").mkdir(parents=True)
(self.local_dir / "models").mkdir(parents=True)
(self.local_dir / "taxonomy").mkdir(parents=True)
# Download project files from storage
all_keys = self.storage.list_recursive(self.prefix)
for key in all_keys:
# key is like users/{uid}/projects/{pid}/uploads/bom.csv
# We want the relative part after the project prefix
rel = key[len(self.prefix) + 1:] # strip prefix + trailing /
local_path = self.local_dir / rel
self.storage.download_to_local(key, local_path)
# Download taxonomy files from storage
taxonomy_keys = self.storage.list_prefix("taxonomy/")
for key in taxonomy_keys:
if key.endswith(".json"):
filename = key.rsplit("/", 1)[-1]
self.storage.download_to_local(key, self.local_dir / "taxonomy" / filename)
# Seed from repo taxonomy if storage had no taxonomy files yet
local_tax = self.local_dir / "taxonomy"
if not any(local_tax.glob("*.json")):
repo_tax = settings.taxonomy_dir
if repo_tax.is_dir():
for f in repo_tax.glob("*.json"):
shutil.copy2(f, local_tax / f.name)
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
# Upload outputs back to storage
self._upload_dir("extracted")
self._upload_dir("patterns")
self._upload_dir("models")
self._upload_file("design_graph.json")
self._upload_file("layout_graph.json")
self._upload_file("impedance_nets.json")
self._upload_file("functional_groups.json")
self._upload_file("placement_plan.json")
self._upload_file("bom_summary.json")
self._upload_file("derating.json")
self._upload_file("report.json")
self._upload_file("periscope-findings.json")
self._upload_file("review_fingerprints.json")
self._upload_file("api_logs.jsonl")
# Merge taxonomy: read current from storage, add any new entries
# from this run, write back. This avoids clobbering subtypes
# that a concurrent pipeline added while we were running.
tax_dir = self.local_dir / "taxonomy"
if tax_dir.is_dir():
for f in tax_dir.iterdir():
if f.is_file() and f.suffix == ".json":
local_data = json.loads(f.read_text())
local_subtypes = local_data.get("subtypes", {})
storage_key = f"taxonomy/{f.name}"
if self.storage.exists(storage_key):
current = self.storage.read_json(storage_key)
merged = current.get("subtypes", {})
for key, entry in local_subtypes.items():
if key not in merged:
merged[key] = entry
else:
# Backfill fields the local run generated
# (e.g. specs_schema) that the
# storage copy is missing.
for field, value in entry.items():
if field not in merged[key]:
merged[key][field] = value
current["subtypes"] = merged
self.storage.write_json(storage_key, current)
else:
self.storage.write_json(storage_key, local_data)
if self._tmpdir:
self._tmpdir.cleanup()
def _upload_dir(self, subdir: str) -> None:
"""Upload all files in a subdirectory back to storage."""
local = self.local_dir / subdir
if not local.is_dir():
return
for f in local.rglob("*"):
if f.is_file():
rel = f.relative_to(self.local_dir)
key = f"{self.prefix}/{rel}"
self.storage.upload_from_local(f, key)
def _upload_file(self, name: str) -> None:
"""Upload a single file back to storage if it exists."""
local = self.local_dir / name
if local.is_file():
self.storage.upload_from_local(local, f"{self.prefix}/{name}")
def local_path(self, rel: str) -> Path:
"""Get a local path within the workspace."""
return self.local_dir / rel
def netlist_local_path(self) -> Path:
"""Local path of whichever netlist file was synced (``.asc`` or ``.edn``).
Pipeline workspace mirrors the entire project prefix, so whichever
format the user uploaded lands locally with its original extension.
Falls back to ``uploads/netlist.asc`` if neither exists downstream
code will raise a clearer error when it tries to read the missing
file than a ``None`` return would.
"""
for ext in ("asc", "edn", "xml", "kicad_net", "kicad_sch"):
p = self.local_dir / "uploads" / f"netlist.{ext}"
if p.exists():
return p
return self.local_dir / "uploads" / "netlist.asc"
@property
def taxonomy_dir(self) -> Path:
return self.local_dir / "taxonomy"
# ---------------------------------------------------------------------------
# Pipeline context — shared state threaded through all stage functions
# ---------------------------------------------------------------------------
@@ -122,7 +122,7 @@ class ProjectMeta(BaseModel):
# Periscope app version that generated the project's report.
# Stamped on the first /start transition and preserved thereafter.
# Accept legacy pinscope_version from project.json written before the rebrand.
# Dual-read pinscope_version (PinScope fence); serialization uses periscope_version.
periscope_version: str | None = Field(
default=None,
validation_alias=AliasChoices("periscope_version", "pinscope_version"),
@@ -143,6 +143,12 @@ class ProjectMeta(BaseModel):
placement_execution_name: str | None = None
placement_cancel_requested: bool = False
# PCB review pipeline (parallel exam — does not overwrite analysis status).
pcb_status: str = "draft"
pcb_state: dict[str, Any] | None = None
pcb_execution_name: str | None = None
pcb_cancel_requested: bool = False
def completed_review_refs_for_retry(
storage: StorageBackend, user_id: str, project_id: str,
@@ -195,10 +201,24 @@ def _read_meta_with_generation(
return ProjectMeta.model_validate(data), gen
def _write_meta(storage: StorageBackend, meta: ProjectMeta) -> None:
def _write_meta(
storage: StorageBackend,
meta: ProjectMeta,
*,
owner_user_id: str | None = None,
) -> None:
"""Persist meta under ``users/{owner}/projects/{id}/``.
``meta.user_id`` can lag the storage prefix (local-auth accounts that
still have ``user_id: "local"`` in JSON while files live under
``users/usr_/``). Writes must follow the prefix used to *read* the
project, not the stale field otherwise ``update_project(pcb_status=)``
lands in a different tree and the PCB worker still sees ``draft``.
"""
uid = owner_user_id or meta.user_id
meta.updated = datetime.now(timezone.utc).isoformat()
storage.write_json(
_meta_key(meta.user_id, meta.id),
_meta_key(uid, meta.id),
meta.model_dump(),
)
@@ -288,34 +308,30 @@ def mark_stale_running(
def heal_if_pipeline_finished(
storage: StorageBackend, user_id: str, project_id: str,
) -> ProjectMeta | None:
"""If meta says queued/running but events already ended with
``pipeline_complete``, flip status to ``complete``.
"""Unstick analysis ``queued``/``running`` when the worker is gone.
Covers zombies where the worker wrote the terminal event (and often
the report) then died before the meta transition e.g. container
rebuild mid-shutdown. Returns updated meta, or ``None`` if no heal.
- Last event ``pipeline_complete`` ``complete``
- Dead worker + ``report.json`` ``complete``
- Dead worker otherwise ``error`` (so PCB/placement can start)
"""
meta = get_project(storage, user_id, project_id)
if meta is None or meta.status not in (STATUS_RUNNING, STATUS_QUEUED):
return None
events_prefix = f"{_project_prefix(user_id, project_id)}/events/"
prefix = _project_prefix(user_id, project_id)
events_prefix = f"{prefix}/events/"
last = None
try:
keys = storage.list_prefix(events_prefix)
except Exception:
return None
event_keys = sorted(
k for k in keys if k.endswith(".json") and "/events/" in k
k for k in storage.list_prefix(events_prefix)
if k.endswith(".json") and "/events/" in k
)
if not event_keys:
return None
try:
if event_keys:
last = storage.read_json(event_keys[-1])
except Exception:
return None
if (last or {}).get("event") != "pipeline_complete":
return None
last = None
if (last or {}).get("event") == "pipeline_complete":
summary = (last.get("data") or {}).get("summary")
try:
return transition_status(
@@ -329,6 +345,32 @@ def heal_if_pipeline_finished(
except StatusConflict:
return None
from backend.services import job_runner
exec_name = meta.execution_name or f"local/projects/{project_id}"
try:
state = job_runner.get_execution_state(exec_name)
except Exception:
state = "unknown"
if state in ("pending", "running"):
return None
if storage.exists(f"{prefix}/report.json"):
try:
return transition_status(
storage, user_id, project_id,
from_status={STATUS_RUNNING, STATUS_QUEUED},
to_status=STATUS_COMPLETE,
cancel_requested=False,
pipeline_state=None,
)
except StatusConflict:
return None
return mark_stale_running(
storage, user_id, project_id,
f"Analysis worker terminated ({state})",
)
def heal_if_placement_stuck(
storage: StorageBackend, user_id: str, project_id: str,
@@ -401,6 +443,70 @@ def heal_if_placement_stuck(
)
def heal_if_pcb_stuck(
storage: StorageBackend, user_id: str, project_id: str,
) -> ProjectMeta | None:
"""Unstick pcb_status queued/running when the worker is gone."""
meta = get_project(storage, user_id, project_id)
if meta is None:
return None
pst = meta.pcb_status or "draft"
if pst not in ("queued", "running"):
return None
prefix = _project_prefix(user_id, project_id)
events_prefix = f"{prefix}/events/"
last_event = None
try:
keys = sorted(
k for k in storage.list_prefix(events_prefix)
if k.endswith(".json") and "/events/" in k
)
if keys:
last_event = storage.read_json(keys[-1])
except Exception:
last_event = None
if (last_event or {}).get("event") == "pcb_complete":
data = (last_event or {}).get("data") or {}
return update_project(
storage, user_id, project_id,
pcb_status="complete",
pcb_cancel_requested=False,
pcb_state={
"findings": data.get("findings"),
"domains": data.get("domains"),
"groups": data.get("groups"),
},
)
from backend.services import job_runner
exec_name = meta.pcb_execution_name or f"local/pcb/{project_id}"
try:
state = job_runner.get_execution_state(exec_name)
except Exception:
state = "unknown"
if state in ("pending", "running"):
return None
has_report = storage.exists(f"{prefix}/pcb_report.json")
if has_report:
return update_project(
storage, user_id, project_id,
pcb_status="complete",
pcb_cancel_requested=False,
pcb_state=meta.pcb_state,
)
return update_project(
storage, user_id, project_id,
pcb_status="error",
pcb_cancel_requested=False,
pcb_state={"error": f"PCB worker terminated ({state})"},
)
# --- CRUD ---
@@ -446,7 +552,7 @@ def update_project(
meta = _read_meta(storage, user_id, project_id)
for k, v in fields.items():
setattr(meta, k, v)
_write_meta(storage, meta)
_write_meta(storage, meta, owner_user_id=user_id)
return meta
@@ -621,7 +727,7 @@ def add_collaborator(
meta = _read_meta(storage, owner_user_id, project_id)
if collaborator_user_id not in meta.collaborators:
meta.collaborators.append(collaborator_user_id)
_write_meta(storage, meta)
_write_meta(storage, meta, owner_user_id=owner_user_id)
# Write reverse reference for the collaborator
ref_key = _shared_ref_key(collaborator_user_id, project_id)
storage.write_json(ref_key, {"owner_user_id": owner_user_id})
@@ -634,7 +740,7 @@ def remove_collaborator(
"""Remove a collaborator from a project and delete the shared reference."""
meta = _read_meta(storage, owner_user_id, project_id)
meta.collaborators = [c for c in meta.collaborators if c != collaborator_user_id]
_write_meta(storage, meta)
_write_meta(storage, meta, owner_user_id=owner_user_id)
# Delete reverse reference
ref_key = _shared_ref_key(collaborator_user_id, project_id)
if storage.exists(ref_key):
@@ -21,12 +21,12 @@ from typing import Awaitable, Callable
log = logging.getLogger(__name__)
from backend.periscopex.finding_engine import apply_decisions
from backend.periscopex.models import (
ComponentConstraints,
ComponentType,
DesignGraph,
Finding,
LayoutGraph,
NetType,
ValidationReport,
)
@@ -61,12 +61,16 @@ from backend.periscopex.dnp_check import check_dnp_enables
from backend.periscopex.lifecycle import check_lifecycle, load_lifecycle_dir
from backend.periscopex.errata_check import check_errata
from backend.periscopex.internal_features_check import check_internal_features
from backend.periscopex.placement_check import check_placement
from backend.periscopex.si_check import check_si
from backend.periscopex.crystal_cl_check import check_crystal_cl
from backend.periscopex.nc_pin_check import check_nc_pins
TRACE_VERSION = 1
from backend.services.review_session import (
TRACE_VERSION,
review_ic_async,
_signal_neighbors,
_select_review_pages,
_assistant_text,
)
def _is_deterministic(f: Finding) -> bool:
@@ -77,7 +81,6 @@ def _is_deterministic(f: Finding) -> bool:
def _run_deterministic_checks(
graph: DesignGraph, constraints_map: dict,
lifecycle_map: dict | None = None,
layout: LayoutGraph | None = None,
) -> list[Finding]:
"""Run the deterministic graph checks, fail-soft per check — a check bug
can never break the review or the report."""
@@ -100,8 +103,6 @@ def _run_deterministic_checks(
("lifecycle_check", lambda: check_lifecycle(graph, lifecycle_map)),
("errata_check", lambda: check_errata(graph, constraints_map)),
("internal_features_check", lambda: check_internal_features(graph, constraints_map)),
("placement_check", lambda: check_placement(graph, constraints_map, layout)),
("si_check", lambda: check_si(graph, constraints_map, layout)),
("crystal_cl_check", lambda: check_crystal_cl(graph)),
("nc_pin_check", lambda: check_nc_pins(graph, constraints_map)),
):
@@ -112,17 +113,6 @@ def _run_deterministic_checks(
return out
def _load_layout_graph(graph_path: str) -> LayoutGraph | None:
path = Path(graph_path).with_name("layout_graph.json")
if not path.is_file():
return None
try:
return LayoutGraph.model_validate_json(path.read_text())
except Exception:
log.exception("layout_graph.json invalid — skipping placement_check")
return None
def _assistant_text(blocks) -> str:
"""Best-effort extraction of text content from a completion's raw
assistant blocks. Provider-agnostic and never raises."""
@@ -301,35 +291,40 @@ def _select_review_pages(pdf_path: str) -> str:
# ---------------------------------------------------------------------------
async def review_ic_async(
# PinScope loop kept for rollback if live native smoke fails. Live path is
# review_ic_async imported from backend.services.review_session.
async def _inherited_review_ic_async(
graph: DesignGraph,
constraints_map: ConstraintsMap,
ic_ref: str,
pdf_path: str,
pdf_path: str | None,
on_progress: ProgressCallback | None = None,
api_logger: ApiLogger | None = None,
trace_git_commit: str = "unknown",
pdf_dir: Path | None = None,
storage=None,
excerpt_cache: dict | None = None,
extra_context: str = "",
system_prompt: str | None = None,
log_stage: str = "review",
) -> tuple[ReviewResult, dict]:
"""Review one IC against its datasheet. Async, multi-turn.
Returns ``(ReviewResult, trace)`` ``trace`` is a transcript dict of the
full agentic loop (turns, tool calls + outputs, final submission) for
offline inspection. Trace assembly is best-effort and never affects the
review result.
``pdf_path`` may be ``None`` when the caller already has library
extraction (PCB layout-only exam) no PDF is attached and citations
are not re-verified against a PDF.
"""
comp = graph.components[ic_ref]
mpn = comp.mpn or comp.value
# Datasheet identity for the trace — hash the original PDF, not the
# trimmed copy, so the reference is stable across trim-heuristic changes.
ds_md5 = None
if pdf_path:
try:
ds_md5 = hashlib.md5(Path(pdf_path).read_bytes()).hexdigest()
except Exception:
log.exception("trace: datasheet md5 failed for %s", ic_ref)
ds_md5 = None
# Pre-compute which designators the excerpt tool will accept for this
# review (neighbors via signal nets only — power/GND fan-out filtered).
@@ -352,7 +347,7 @@ async def review_ic_async(
current_ic=ic_ref,
connected_designators=connected_designators,
graph=graph,
pdf_dir=pdf_dir or Path(pdf_path).parent,
pdf_dir=pdf_dir or (Path(pdf_path).parent if pdf_path else Path(".")),
storage=storage,
cache=excerpt_cache if excerpt_cache is not None else {},
fetch_budget=_PER_REVIEW_FETCH_BUDGET,
@@ -361,7 +356,7 @@ async def review_ic_async(
)
# Trim PDF up-front — both primary and fallback attempts share it.
trimmed_pdf = _select_review_pages(pdf_path)
trimmed_pdf = _select_review_pages(pdf_path) if pdf_path else None
try:
async def _run(provider, model) -> tuple[ReviewResult, dict]:
t0 = time.monotonic()
@@ -373,7 +368,7 @@ async def review_ic_async(
session = await provider.create_session(
model=model,
system=SYSTEM_PROMPT,
system=system_prompt or SYSTEM_PROMPT,
# Gemini 2.5/3 thinking models count thoughts against this cap.
# 4096 was too tight: U3 (largest IC) burned the entire budget
# on thinking and emitted zero visible output, dropping its
@@ -387,16 +382,17 @@ async def review_ic_async(
)
try:
context = build_component_context(graph, constraints_map, ic_ref)
user_text = f"Review this component's usage:\n\n{context}"
if extra_context.strip():
user_text += "\n\n" + extra_context.strip()
user_blocks: list = []
if trimmed_pdf:
user_blocks.append(PdfBlock(path=Path(trimmed_pdf), cacheable=True))
user_blocks.append(TextBlock(text=user_text, cacheable=True))
initial_msg = Message(
role="user",
content=[
PdfBlock(path=Path(trimmed_pdf), cacheable=True),
TextBlock(
text=f"Review this component's usage:\n\n{context}",
cacheable=True,
),
],
content=user_blocks,
)
messages: list[Message] = [initial_msg]
@@ -476,6 +472,7 @@ async def review_ic_async(
mpn_by_designator=mpn_by_designator,
connected=connected_designators,
)
if pdf_path:
verify_finding_citations(
result.findings,
default_pdf=Path(pdf_path),
@@ -503,7 +500,7 @@ async def review_ic_async(
)
if api_logger:
api_logger.log(
stage="review", identifier=ic_ref,
stage=log_stage, identifier=ic_ref,
model=model, provider=provider.name,
input_tokens=total_input, output_tokens=total_output,
cache_creation_input_tokens=total_cache_creation,
@@ -607,7 +604,7 @@ async def review_ic_async(
trace["duration_ms"] = int((time.monotonic() - t0) * 1000)
if api_logger:
api_logger.log(
stage="review", identifier=ic_ref,
stage=log_stage, identifier=ic_ref,
model=model, provider=provider.name,
input_tokens=total_input, output_tokens=total_output,
cache_creation_input_tokens=total_cache_creation,
@@ -621,7 +618,7 @@ async def review_ic_async(
return await call_with_fallback("validation", _run)
finally:
if trimmed_pdf != pdf_path:
if trimmed_pdf and pdf_path and trimmed_pdf != pdf_path:
Path(trimmed_pdf).unlink(missing_ok=True)
@@ -730,7 +727,7 @@ async def validate_design_async(
if loaded:
lifecycle_map.update(loaded)
deterministic_findings = _run_deterministic_checks(
graph, constraints_map, lifecycle_map, layout=_load_layout_graph(graph_path),
graph, constraints_map, lifecycle_map,
)
pdf_dir_path = Path(pdf_dir)
@@ -801,6 +798,12 @@ async def validate_design_async(
def _write_report(paused: bool = False) -> ValidationReport:
annotate_findings_cad(all_findings, graph.cad_index)
assign_finding_ids(all_findings)
dec_path = existing_path.with_name("decisions.json")
if dec_path.is_file():
try:
apply_decisions(all_findings, json.loads(dec_path.read_text()))
except Exception:
log.exception("decisions.json apply failed")
summary = {"total": len(all_findings), "ERROR": 0, "WARNING": 0, "INFO": 0}
for f in all_findings:
summary[f.status] = summary.get(f.status, 0) + 1
@@ -1,5 +1,5 @@
{
"default_model_version": "1.10.0",
"default_model_version": "1.13.0",
"extract-pintable": {
"skill_id": "skill_01VMWPZuvuZAe4LmLbmsNWNY",
"latest_version": "1784798970179642",

Before

Width:  |  Height:  |  Size: 6.9 KiB

After

Width:  |  Height:  |  Size: 6.9 KiB

Some files were not shown because too many files have changed in this diff Show More