chore: add community files, CI workflows, and host test tooling
Add the repository-facing scaffolding: - Community/legal: README.md, LICENSE (GPL-3.0-or-later), NOTICE, CONTRIBUTING.md, SECURITY.md, CODE_OF_CONDUCT.md, .gitleaks.toml - CI: .github/ workflows (ci.yml aggregate gate, nightly.yml, codeql.yml), issue/PR templates, dependabot config (pinned Actions per README) - Host tooling: tools/frame_tools (ruff/pyright/pytest gates, partition, evidence-schema, doc-links, SBOM checks), tests/, pyproject.toml, uv.lock - poc/ host side: poc/host contract-test suite (ASan/TSan-capable), poc/README.md, poc/poc-a.code-workspace Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <[email protected]>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Local repository gates for Frame."""
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Enforce LLVM branch coverage for the shared Frame contract headers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def branch_percentage(report: Path) -> float:
|
||||
data = json.loads(report.read_text(encoding="utf-8"))
|
||||
try:
|
||||
return float(data["data"][0]["totals"]["branches"]["percent"])
|
||||
except (KeyError, IndexError, TypeError, ValueError) as error:
|
||||
raise ValueError(f"{report}: invalid llvm-cov export") from error
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Check Frame LLVM branch coverage")
|
||||
parser.add_argument("report", type=Path)
|
||||
parser.add_argument("--minimum", type=float, default=90.0)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
percentage = branch_percentage(args.report)
|
||||
except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
if percentage < args.minimum:
|
||||
print(
|
||||
f"branch coverage {percentage:.2f}% is below {args.minimum:.2f}%",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
print(f"branch coverage {percentage:.2f}% meets {args.minimum:.2f}%")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Check local targets and Markdown heading fragments in repository documentation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable, Sequence
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
LINK_PATTERN = re.compile(r"!?\[[^]]*]\(\s*(<[^>]+>|[^\s)]+)(?:\s+[^)]*)?\)")
|
||||
HEADING_PATTERN = re.compile(r"^#{1,6}\s+(.+?)\s*#*\s*$")
|
||||
INLINE_CODE_PATTERN = re.compile(r"`+[^`]*`+")
|
||||
IGNORED_DIRECTORIES = {
|
||||
".build",
|
||||
".cache",
|
||||
".git",
|
||||
".opencode",
|
||||
".pytest_cache",
|
||||
".venv",
|
||||
".venv-idf",
|
||||
"build",
|
||||
"managed_components",
|
||||
}
|
||||
|
||||
|
||||
def _slug(text: str) -> str:
|
||||
text = re.sub(r"<[^>]*>", "", text)
|
||||
text = re.sub(r"!\[[^]]*]\([^)]*\)", "", text)
|
||||
text = re.sub(r"\[([^]]*)]\([^)]*\)", r"\1", text)
|
||||
text = re.sub(r"[`*_~]", "", text).strip().lower()
|
||||
text = re.sub(r"[^\w\- ]", "", text)
|
||||
return re.sub(r"\s", "-", text)
|
||||
|
||||
|
||||
def markdown_anchors(path: Path) -> set[str]:
|
||||
anchors: set[str] = set()
|
||||
seen: Counter[str] = Counter()
|
||||
in_fence = False
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
stripped = line.lstrip()
|
||||
if stripped.startswith(("```", "~~~")):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
match = HEADING_PATTERN.match(line)
|
||||
if match is None:
|
||||
continue
|
||||
base = _slug(match.group(1))
|
||||
duplicate = seen[base]
|
||||
seen[base] += 1
|
||||
anchors.add(base if duplicate == 0 else f"{base}-{duplicate}")
|
||||
return anchors
|
||||
|
||||
|
||||
def _markdown_files(root: Path, inputs: Sequence[Path]) -> tuple[list[Path], list[str]]:
|
||||
files: list[Path] = []
|
||||
errors: list[str] = []
|
||||
sources = list(inputs) if inputs else [root]
|
||||
for source in sources:
|
||||
if source.is_file() and source.suffix.lower() == ".md":
|
||||
files.append(source)
|
||||
elif source.is_dir():
|
||||
for path in source.rglob("*.md"):
|
||||
try:
|
||||
relative_parts = path.relative_to(root).parts
|
||||
except ValueError:
|
||||
relative_parts = path.parts
|
||||
if not any(part in IGNORED_DIRECTORIES for part in relative_parts):
|
||||
files.append(path)
|
||||
else:
|
||||
errors.append(f"{source}: documentation path does not exist or is not Markdown")
|
||||
return sorted(set(files), key=lambda path: str(path)), errors
|
||||
|
||||
|
||||
def _links(path: Path) -> Iterable[tuple[int, str]]:
|
||||
in_fence = False
|
||||
for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
||||
stripped = line.lstrip()
|
||||
if stripped.startswith(("```", "~~~")):
|
||||
in_fence = not in_fence
|
||||
continue
|
||||
if in_fence:
|
||||
continue
|
||||
line = INLINE_CODE_PATTERN.sub("", line)
|
||||
for match in LINK_PATTERN.finditer(line):
|
||||
target = match.group(1)
|
||||
yield line_number, target[1:-1] if target.startswith("<") else target
|
||||
|
||||
|
||||
def validate_doc_links(root: Path, paths: Sequence[Path] = ()) -> list[str]:
|
||||
root = root.resolve()
|
||||
markdown_files, errors = _markdown_files(root, paths)
|
||||
anchor_cache: dict[Path, set[str]] = {}
|
||||
|
||||
for source in markdown_files:
|
||||
try:
|
||||
links = list(_links(source))
|
||||
except (OSError, UnicodeError) as error:
|
||||
errors.append(f"{source}: cannot read Markdown: {error}")
|
||||
continue
|
||||
|
||||
for line_number, raw_target in links:
|
||||
parsed = urlsplit(raw_target)
|
||||
if parsed.scheme or parsed.netloc:
|
||||
continue
|
||||
relative_target = Path(unquote(parsed.path))
|
||||
if not parsed.path:
|
||||
target = source.resolve()
|
||||
elif parsed.path.startswith("/"):
|
||||
target = (root / str(relative_target).lstrip("/")).resolve(strict=False)
|
||||
else:
|
||||
target = (source.parent / relative_target).resolve(strict=False)
|
||||
|
||||
if not target.is_relative_to(root):
|
||||
errors.append(
|
||||
f"{source}:{line_number}: local link escapes repository: {raw_target}"
|
||||
)
|
||||
continue
|
||||
if not target.exists():
|
||||
errors.append(
|
||||
f"{source}:{line_number}: local link target does not exist: {raw_target}"
|
||||
)
|
||||
continue
|
||||
if parsed.fragment and target.suffix.lower() == ".md":
|
||||
anchors = anchor_cache.setdefault(target, markdown_anchors(target))
|
||||
fragment = unquote(parsed.fragment)
|
||||
if fragment not in anchors:
|
||||
errors.append(
|
||||
f"{source}:{line_number}: Markdown anchor does not exist: {raw_target}"
|
||||
)
|
||||
return errors
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Validate local links in Markdown files")
|
||||
parser.add_argument("paths", nargs="*", type=Path, help="Markdown files or directories")
|
||||
parser.add_argument("--root", type=Path, default=Path.cwd(), help="repository root")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
errors = validate_doc_links(args.root, args.paths)
|
||||
if errors:
|
||||
print("\n".join(errors), file=sys.stderr)
|
||||
return 1
|
||||
print("documentation links are valid")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Validate PoC evidence manifests against the repository JSON Schema."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from jsonschema import FormatChecker, SchemaError
|
||||
from jsonschema.validators import validator_for
|
||||
|
||||
|
||||
def _load_json(path: Path) -> Any:
|
||||
with path.open(encoding="utf-8") as stream:
|
||||
return json.load(stream)
|
||||
|
||||
|
||||
def _json_path(parts: Sequence[object]) -> str:
|
||||
return "$" + "".join(f"[{part!r}]" for part in parts)
|
||||
|
||||
|
||||
def validate_evidence(schema_path: Path, manifest_paths: Sequence[Path]) -> list[str]:
|
||||
try:
|
||||
schema = _load_json(schema_path)
|
||||
validator_class = validator_for(schema)
|
||||
validator_class.check_schema(schema)
|
||||
validator = validator_class(schema, format_checker=FormatChecker())
|
||||
except (OSError, UnicodeError, json.JSONDecodeError, SchemaError) as error:
|
||||
return [f"{schema_path}: invalid evidence schema: {error}"]
|
||||
|
||||
errors: list[str] = []
|
||||
for path in manifest_paths:
|
||||
try:
|
||||
manifest = _load_json(path)
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as error:
|
||||
errors.append(f"{path}: invalid JSON: {error}")
|
||||
continue
|
||||
|
||||
validation_errors = sorted(
|
||||
validator.iter_errors(manifest), key=lambda item: _json_path(list(item.path))
|
||||
)
|
||||
errors.extend(
|
||||
f"{path}:{_json_path(list(error.path))}: {error.message}" for error in validation_errors
|
||||
)
|
||||
return errors
|
||||
|
||||
|
||||
def discover_manifests(inputs: Sequence[Path], schema_path: Path) -> tuple[list[Path], list[str]]:
|
||||
candidates: list[Path] = []
|
||||
errors: list[str] = []
|
||||
sources = list(inputs) if inputs else [Path("poc/evidence")]
|
||||
schema_resolved = schema_path.resolve(strict=False)
|
||||
|
||||
for source in sources:
|
||||
if source.is_dir():
|
||||
candidates.extend(sorted(source.rglob("*.json")))
|
||||
elif source.is_file():
|
||||
candidates.append(source)
|
||||
else:
|
||||
errors.append(f"{source}: evidence path does not exist")
|
||||
|
||||
manifests = sorted(
|
||||
{path for path in candidates if path.resolve(strict=False) != schema_resolved},
|
||||
key=lambda path: str(path),
|
||||
)
|
||||
return manifests, errors
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Validate Frame evidence manifests")
|
||||
parser.add_argument("paths", nargs="*", type=Path, help="manifest files or directories")
|
||||
parser.add_argument(
|
||||
"--schema",
|
||||
type=Path,
|
||||
default=Path("poc/evidence/schema.json"),
|
||||
help="evidence JSON Schema",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
manifests, errors = discover_manifests(args.paths, args.schema)
|
||||
errors.extend(validate_evidence(args.schema, manifests))
|
||||
if errors:
|
||||
print("\n".join(errors), file=sys.stderr)
|
||||
return 1
|
||||
print(f"validated evidence schema and {len(manifests)} manifest(s)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Collect M1 hardware-validation evidence from the device serial console.
|
||||
|
||||
The collector passively records everything on the console into ``soak.log``,
|
||||
splits device JSON lines into ``jsonl.ndjson`` (telemetry) and ``status.json``
|
||||
(``status --json`` responses), and writes a draft ``manifest.json`` for the M1
|
||||
gate whose verdict is completed later by the soak judgment step.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import importlib
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Protocol, cast
|
||||
|
||||
SOAK_LOG = "soak.log"
|
||||
JSONL_LOG = "jsonl.ndjson"
|
||||
STATUS_LOG = "status.json"
|
||||
MANIFEST_LOG = "manifest.json"
|
||||
STATUS_COMMAND = b"status --json\r\n"
|
||||
|
||||
|
||||
class LineKind(Enum):
|
||||
RAW = "raw"
|
||||
JSONL = "jsonl"
|
||||
STATUS = "status"
|
||||
|
||||
|
||||
def parse_device_json(line: str) -> dict[str, object] | None:
|
||||
"""Return the decoded device JSON object, or None for plain console text."""
|
||||
text = line.strip()
|
||||
if not text.startswith("{"):
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return payload if isinstance(payload, dict) else None
|
||||
|
||||
|
||||
def classify_payload(payload: dict[str, object]) -> LineKind:
|
||||
"""Telemetry lines carry ``sequence``; status responses do not."""
|
||||
if payload.get("schema_version") != 1:
|
||||
return LineKind.RAW
|
||||
return LineKind.JSONL if "sequence" in payload else LineKind.STATUS
|
||||
|
||||
|
||||
def sequence_of(payload: dict[str, object]) -> int | None:
|
||||
value = payload.get("sequence")
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CaptureStats:
|
||||
jsonl_count: int = 0
|
||||
sequence_min: int | None = None
|
||||
sequence_max: int | None = None
|
||||
|
||||
def record(self, payload: dict[str, object]) -> None:
|
||||
self.jsonl_count += 1
|
||||
sequence = sequence_of(payload)
|
||||
if sequence is not None:
|
||||
self.sequence_min = (
|
||||
sequence if self.sequence_min is None else min(self.sequence_min, sequence)
|
||||
)
|
||||
self.sequence_max = (
|
||||
sequence if self.sequence_max is None else max(self.sequence_max, sequence)
|
||||
)
|
||||
|
||||
def as_metrics(self) -> dict[str, int]:
|
||||
metrics = {"jsonl_count": self.jsonl_count}
|
||||
if self.sequence_min is not None:
|
||||
metrics["sequence_min"] = self.sequence_min
|
||||
if self.sequence_max is not None:
|
||||
metrics["sequence_max"] = self.sequence_max
|
||||
return metrics
|
||||
|
||||
|
||||
class SerialPort(Protocol):
|
||||
def readline(self) -> bytes: ...
|
||||
|
||||
def write(self, data: bytes) -> int: ...
|
||||
|
||||
def close(self) -> None: ...
|
||||
|
||||
|
||||
class SerialFactory(Protocol):
|
||||
def __call__(self, port: str, baudrate: int, timeout: float) -> SerialPort: ...
|
||||
|
||||
|
||||
def load_serial() -> SerialFactory:
|
||||
"""Import pyserial lazily; it is an optional, capture-only dependency."""
|
||||
try:
|
||||
module = importlib.import_module("serial")
|
||||
except ImportError as error:
|
||||
raise SystemExit(
|
||||
"pyserial is required for serial capture but is not installed; "
|
||||
"install it into the active environment with `uv pip install pyserial`"
|
||||
) from error
|
||||
# pyserial is absent from the checked-in dependency set, so bind it to a
|
||||
# Protocol at this boundary instead of importing it for type checking.
|
||||
return cast(SerialFactory, module.Serial)
|
||||
|
||||
|
||||
def _sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for chunk in iter(lambda: stream.read(65536), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _utc_now() -> str:
|
||||
return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
class CaptureWriter:
|
||||
"""Route decoded serial lines into the soak, JSONL, and status artifacts."""
|
||||
|
||||
def __init__(self, out_dir: Path) -> None:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._out_dir = out_dir
|
||||
self._soak = (out_dir / SOAK_LOG).open("w", encoding="utf-8")
|
||||
self._jsonl = (out_dir / JSONL_LOG).open("w", encoding="utf-8")
|
||||
self._status = (out_dir / STATUS_LOG).open("w", encoding="utf-8")
|
||||
self.stats = CaptureStats()
|
||||
|
||||
def __enter__(self) -> CaptureWriter:
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> None:
|
||||
self.close()
|
||||
|
||||
def close(self) -> None:
|
||||
for stream in (self._soak, self._jsonl, self._status):
|
||||
stream.close()
|
||||
|
||||
def process_line(self, line: str) -> None:
|
||||
text = line.rstrip("\r\n")
|
||||
self._soak.write(f"{text}\n")
|
||||
payload = parse_device_json(text)
|
||||
if payload is None:
|
||||
return
|
||||
match classify_payload(payload):
|
||||
case LineKind.JSONL:
|
||||
self.stats.record(payload)
|
||||
self._jsonl.write(f"{text}\n")
|
||||
case LineKind.STATUS:
|
||||
self._status.write(f"{text}\n")
|
||||
case LineKind.RAW:
|
||||
pass
|
||||
|
||||
def write_manifest(self, run_id: str, started_at: str, ended_at: str) -> Path:
|
||||
"""Write the collector draft manifest; the soak step completes the verdict."""
|
||||
for stream in (self._soak, self._jsonl, self._status):
|
||||
stream.flush()
|
||||
manifest = {
|
||||
"schema_version": 1,
|
||||
"gate": "M1",
|
||||
"run_id": run_id,
|
||||
"verdict": "pending",
|
||||
"started_at": started_at,
|
||||
"ended_at": ended_at,
|
||||
"metrics": self.stats.as_metrics(),
|
||||
"artifacts": [
|
||||
{"name": name, "uri": name, "sha256": _sha256(self._out_dir / name)}
|
||||
for name in (SOAK_LOG, JSONL_LOG, STATUS_LOG)
|
||||
],
|
||||
"notes": "collector draft; verdict, source, and platform are completed later",
|
||||
}
|
||||
path = self._out_dir / MANIFEST_LOG
|
||||
path.write_text(f"{json.dumps(manifest, indent=2)}\n", encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CaptureSettings:
|
||||
port: str
|
||||
baud: int
|
||||
duration: float
|
||||
out_dir: Path
|
||||
status_interval: float
|
||||
|
||||
|
||||
def _pump(port: SerialPort, writer: CaptureWriter, settings: CaptureSettings) -> None:
|
||||
deadline = time.monotonic() + settings.duration
|
||||
next_status = time.monotonic() + settings.status_interval
|
||||
while time.monotonic() < deadline:
|
||||
if time.monotonic() >= next_status:
|
||||
port.write(STATUS_COMMAND)
|
||||
next_status += settings.status_interval
|
||||
line = port.readline()
|
||||
if line:
|
||||
writer.process_line(line.decode("utf-8", errors="replace"))
|
||||
|
||||
|
||||
def run_capture(settings: CaptureSettings, open_port: SerialFactory) -> Path:
|
||||
"""Capture for ``settings.duration`` seconds and return the manifest path."""
|
||||
started_at = _utc_now()
|
||||
run_id = f"m1-{datetime.now(UTC).strftime('%Y%m%dT%H%M%SZ')}"
|
||||
port = open_port(settings.port, baudrate=settings.baud, timeout=1.0)
|
||||
try:
|
||||
with CaptureWriter(settings.out_dir) as writer:
|
||||
try:
|
||||
_pump(port, writer, settings)
|
||||
finally:
|
||||
manifest_path = writer.write_manifest(run_id, started_at, _utc_now())
|
||||
return manifest_path
|
||||
finally:
|
||||
port.close()
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Collect M1 gate evidence from the serial console")
|
||||
parser.add_argument(
|
||||
"--port", default="/dev/ttyACM0", help="serial device (default: %(default)s)"
|
||||
)
|
||||
parser.add_argument("--baud", type=int, default=115200, help="baud rate (default: %(default)s)")
|
||||
parser.add_argument(
|
||||
"--duration", type=float, required=True, help="capture length in seconds (soak mode)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--out", type=Path, required=True, help="output directory for captured artifacts"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--status-interval",
|
||||
type=float,
|
||||
default=120.0,
|
||||
help="seconds between status --json polls (default: %(default)s)",
|
||||
)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
settings = CaptureSettings(
|
||||
port=args.port,
|
||||
baud=args.baud,
|
||||
duration=args.duration,
|
||||
out_dir=args.out,
|
||||
status_interval=args.status_interval,
|
||||
)
|
||||
try:
|
||||
manifest_path = run_capture(settings, load_serial())
|
||||
except OSError as error:
|
||||
print(f"{settings.port}: cannot open serial port: {error}", file=sys.stderr)
|
||||
return 1
|
||||
print(f"{manifest_path}: capture complete")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Validate the frozen 16 MiB Frame partition layout."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
EXPECTED_HEADER = ("# Name", "Type", "SubType", "Offset", "Size", "Flags")
|
||||
EXPECTED_PARTITIONS = (
|
||||
("nvs", "data", "nvs", "0x9000", "0x14000", ""),
|
||||
("nvs_keys", "data", "nvs_keys", "0x1D000", "0x1000", "encrypted"),
|
||||
("otadata", "data", "ota", "0x1E000", "0x2000", ""),
|
||||
("coredump", "data", "coredump", "0x20000", "0x20000", ""),
|
||||
("ota_0", "app", "ota_0", "0x40000", "0x500000", ""),
|
||||
("ota_1", "app", "ota_1", "0x540000", "0x500000", ""),
|
||||
("plugin_fs", "data", "littlefs", "0xA40000", "0x4C0000", ""),
|
||||
("system_fs", "data", "littlefs", "0xF00000", "0x100000", ""),
|
||||
)
|
||||
|
||||
|
||||
def read_layout(path: Path) -> tuple[tuple[str, ...], ...]:
|
||||
with path.open(encoding="utf-8", newline="") as stream:
|
||||
rows = csv.reader(stream, skipinitialspace=True)
|
||||
return tuple(
|
||||
tuple(cell.strip() for cell in row) for row in rows if any(cell.strip() for cell in row)
|
||||
)
|
||||
|
||||
|
||||
def validate_partitions(path: Path) -> list[str]:
|
||||
try:
|
||||
rows = read_layout(path)
|
||||
except (OSError, UnicodeError, csv.Error) as error:
|
||||
return [f"{path}: cannot read partition CSV: {error}"]
|
||||
|
||||
expected = (EXPECTED_HEADER, *EXPECTED_PARTITIONS)
|
||||
if rows == expected:
|
||||
return []
|
||||
|
||||
errors: list[str] = []
|
||||
if not rows:
|
||||
return [f"{path}: partition CSV is empty"]
|
||||
if rows[0] != EXPECTED_HEADER:
|
||||
errors.append(f"{path}: header changed: expected {EXPECTED_HEADER!r}, got {rows[0]!r}")
|
||||
|
||||
actual_partitions = rows[1:]
|
||||
for index in range(max(len(actual_partitions), len(EXPECTED_PARTITIONS))):
|
||||
expected_row = EXPECTED_PARTITIONS[index] if index < len(EXPECTED_PARTITIONS) else None
|
||||
actual_row = actual_partitions[index] if index < len(actual_partitions) else None
|
||||
if actual_row != expected_row:
|
||||
errors.append(
|
||||
f"{path}: partition row {index + 1} changed: "
|
||||
f"expected {expected_row!r}, got {actual_row!r}"
|
||||
)
|
||||
return errors
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Validate the frozen Frame partition table")
|
||||
parser.add_argument("path", nargs="?", type=Path, default=Path("partitions.csv"))
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
errors = validate_partitions(args.path)
|
||||
if errors:
|
||||
print("\n".join(errors), file=sys.stderr)
|
||||
return 1
|
||||
print(f"{args.path}: partition layout matches the frozen layout")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Validate pull request titles without granting pull request code extra permissions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
|
||||
TITLE_PATTERN = re.compile(
|
||||
r"^(?:build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)"
|
||||
r"(?:\([a-z0-9][a-z0-9._/-]*\))?!?: \S.*$"
|
||||
)
|
||||
|
||||
|
||||
def validate_title(title: str) -> str | None:
|
||||
"""Return a diagnostic when a PR title does not follow the repository convention."""
|
||||
if title != title.strip() or "\n" in title or "\r" in title:
|
||||
return "PR title must be a single line without leading or trailing whitespace"
|
||||
if not TITLE_PATTERN.fullmatch(title):
|
||||
return (
|
||||
"PR title must use '<type>(optional-scope): summary'; allowed types are "
|
||||
"build, chore, ci, docs, feat, fix, perf, refactor, revert, style, and test"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Validate a Frame pull request title")
|
||||
parser.add_argument("--title", help="title to validate; defaults to the PR_TITLE environment")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
title = args.title if args.title is not None else os.environ.get("PR_TITLE")
|
||||
if title is None:
|
||||
parser.error("--title or PR_TITLE is required")
|
||||
|
||||
error = validate_title(title)
|
||||
if error is not None:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
print("PR title is valid")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Generate a deterministic CycloneDX inventory from Frame lock files."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import tomllib
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
def _component(
|
||||
name: str, version: str, ecosystem: str, digest: str | None = None
|
||||
) -> dict[str, object]:
|
||||
item: dict[str, object] = {
|
||||
"type": "library",
|
||||
"bom-ref": f"pkg:{ecosystem}/{name}@{version}",
|
||||
"name": name,
|
||||
"version": version,
|
||||
"purl": f"pkg:{ecosystem}/{name}@{version}",
|
||||
}
|
||||
if digest is not None:
|
||||
item["hashes"] = [{"alg": "SHA-256", "content": digest}]
|
||||
return item
|
||||
|
||||
|
||||
def locked_components(root: Path) -> list[dict[str, object]]:
|
||||
components: dict[str, dict[str, object]] = {}
|
||||
uv_data = tomllib.loads((root / "uv.lock").read_text(encoding="utf-8"))
|
||||
for package in uv_data.get("package", []):
|
||||
name = package.get("name")
|
||||
version = package.get("version")
|
||||
if not isinstance(name, str) or not isinstance(version, str) or name == "frame-tools":
|
||||
continue
|
||||
item = _component(name, version, "pypi")
|
||||
components[str(item["bom-ref"])] = item
|
||||
|
||||
lock_files = [root / "dependencies.lock", root / "poc/apps/m1_hardware/dependencies.lock"]
|
||||
for path in lock_files:
|
||||
data = yaml.safe_load(path.read_text(encoding="utf-8"))
|
||||
for name, package in data.get("dependencies", {}).items():
|
||||
if name == "idf":
|
||||
continue
|
||||
version = str(package["version"])
|
||||
digest = package.get("component_hash")
|
||||
item = _component(name, version, "espressif", digest)
|
||||
components[str(item["bom-ref"])] = item
|
||||
|
||||
idf = _component("esp-idf", "6.0.2", "github/espressif")
|
||||
components[str(idf["bom-ref"])] = idf
|
||||
googletest = _component(
|
||||
"google/googletest", "52eb8108c5bdec04579160ae17225d66034bd723", "github"
|
||||
)
|
||||
components[str(googletest["bom-ref"])] = googletest
|
||||
return [components[key] for key in sorted(components)]
|
||||
|
||||
|
||||
def generate_sbom(root: Path) -> dict[str, object]:
|
||||
return {
|
||||
"bomFormat": "CycloneDX",
|
||||
"specVersion": "1.5",
|
||||
"serialNumber": "urn:uuid:ba788506-18cf-5a4e-ae35-38d141e6db90",
|
||||
"version": 1,
|
||||
"metadata": {
|
||||
"component": {
|
||||
"type": "application",
|
||||
"bom-ref": "pkg:github/Aniakea/frame",
|
||||
"name": "Frame",
|
||||
"version": "0.1.0-dev.1",
|
||||
}
|
||||
},
|
||||
"components": locked_components(root),
|
||||
}
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Generate the Frame CycloneDX SBOM")
|
||||
parser.add_argument("--root", type=Path, default=Path.cwd())
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
output = json.dumps(generate_sbom(args.root.resolve()), indent=2, sort_keys=True) + "\n"
|
||||
except (
|
||||
OSError,
|
||||
UnicodeError,
|
||||
ValueError,
|
||||
KeyError,
|
||||
TypeError,
|
||||
tomllib.TOMLDecodeError,
|
||||
) as error:
|
||||
print(error, file=sys.stderr)
|
||||
return 1
|
||||
if args.output is None:
|
||||
sys.stdout.write(output)
|
||||
else:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(output, encoding="utf-8")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user