{"id":"primitive_foundry.audit.audit_local_paths::explain","input":"Module: primitive_foundry.audit\nDomains: privacy, release, marketplace, commercial, bus, planner, dataset, router, benchmark, source_card, product_factory\nSource path: primitive_foundry/audit.py\n\ndef audit_local_paths(work_dir: str | Path = \".\") -> dict[str, Any]:\n root = Path(work_dir)\n artifacts = root / artifact_root()\n lock_path = root / \".audit.lock\"\n lock_fd: int | None = None\n try:\n lock_fd = os.open(lock_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)\n os.write(lock_fd, str(os.getpid()).encode(\"utf-8\"))\n atexit.register(lambda: lock_path.exists() and lock_path.unlink())\n except FileExistsError:\n return {\n \"audit\": \"aml_local_paths\",\n \"passed\": False,\n \"checks\": [\n {\n \"name\": \"audit_lock\",\n \"passed\": False,\n \"detail\": f\"Another audit is already running or stale lock exists: {lock_path}\",\n }\n ],\n }\n checks = []\n\n def add(name: str, passed: bool, detail: Any) -> None:\n checks.append({\"name\": name, \"passed\": passed, \"detail\": detail})\n\n v03 = root / \"datasets/v0.3/aml_v0_3.jsonl\"\n v04_train = root / \"datasets/v0.4/train.jsonl\"\n v04_hard = root / \"datasets/v0.4/hard.jsonl\"\n pre_registry = root / \"registries/v0.4/pre_replacement.json\"\n events = root / \"events/v0.3/lifecycle_events.jsonl\"\n applied_registry = root / \"registries/v0.4/post_from_events.json\"\n model = root / \"models/router_v0_1.json\"\n\n add(\"load_v03_dataset\", len(load_jsonl(v03)) == 150, str(v03))\n add(\"load_v04_hard_dataset\", len(load_jsonl(v04_hard)) == 72, str(v04_hard))\n\n pre = CellRegistry.from_json(pre_registry)\n add(\"pre_registry_loads\", pre.current_for_domain(\"finance.tax\").cell_id == \"finance.tax.2023\", str(pre_registry))\n\n apply_result = apply_lifecycle_events(pre_registry, events, applied_registry, \"audit-event-applied\")\n applied = CellRegistry.from_json(applied_registry)\n add(\n \"apply_events_registry\",\n apply_result[\"applied_count\"] == 10 and applied.current_for_domain(\"finance.tax\").cell_id == \"finance.tax.2024\",\n apply_result,\n )\n\n transition = simulate_registry_transition(v04_hard, pre_registry, applied_registry)\n add(\n \"transition_executes\",\n transition[\"changed_count\"] == transition[\"record_count\"] and transition[\"post_match_rate\"] == 1.0,\n {\n \"record_count\": transition[\"record_count\"],\n \"changed_count\": transition[\"changed_count\"],\n \"post_match_rate\": transition[\"post_match_rate\"],\n },\n )\n\n post_report = BenchmarkRunner(router_name=\"keyword\", registry_path=applied_registry).run_dataset(v04_hard)\n add(\"post_applied_registry_benchmark\", post_report[\"pass_rate\"] == 1.0, post_report[\"pass_rate\"])\n\n train_centroid_router(v04_train, model)\n trained_report = BenchmarkRunner(router_name=\"trained\", router_path=model).run_dataset(root / \"datasets/v0.4/eval.jsonl\")\n add(\"trained_router_executes\", trained_report[\"pass_rate\"] == 1.0, trained_report[\"pass_rate\"])\n\n summary = router_summary(v04_hard, model)\n add(\"summary_executes\", len(summary[\"rows\"]) == 3, [row[\"router\"] for row in summary[\"rows\"]])\n\n foundry_records = artifacts / \"releases/foundry-compatible/aml_v0_4_foundry.jsonl\"\n foundry_bundle = artifacts / \"releases/foundry-compatible/aml_context_lifecycle_0.4.0_bundle_000001\"\n export_result = export_foundry_records(v04_hard, foundry_records)\n verify_result = verify_foundry_records(foundry_records)\n bundle_result = build_foundry_bundle(foundry_records, foundry_bundle)\n bundle_verify = verify_foundry_bundle(foundry_bundle)\n add(\n \"foundry_export_verify_bundle\",\n export_result[\"quality\"][\"passed\"]\n and verify_result[\"passed\"]\n and bundle_result[\"quality\"][\"passed\"]\n and bundle_verify[\"passed\"],\n {\n \"records\": str(foundry_records),\n \"bundle\": str(foundry_bundle),\n \"record_count\": bundle_result[\"record_count\"],\n },\n )\n\n source_cards = root / \"sources/v0.5/source_cards.jsonl\"\n source_dataset = root / \"datasets/v0.5/source_backed.jsonl\"\n source_foundry = artifacts / \"releases/foundry-compatible/aml_v0_5_source_backed_foundry.jsonl\"\n source_bundle = artifacts / \"releases/foundry-compatible/aml_context_lifecycle_0.5.0_source_backed_bundle_000001\"\n curated = curate_source_cards(source_cards, source_dataset)\n source_export = export_foundry_records(source_dataset, source_foundry)\n source_bundle_result = build_foundry_bundle(source_foundry, source_bundle)\n source_bundle_verify = verify_foundry_bundle(source_bundle)\n add(\n \"source_backed_curate_export_bundle\",\n curated[\"record_count\"] == 6\n and source_export[\"quality\"][\"passed\"]\n and source_bundle_result[\"quality\"][\"passed\"]\n and source_bundle_verify[\"passed\"],\n {\n \"dataset\": str(source_dataset),\n \"bundle\": str(source_bundle),\n \"record_count\": curated[\"record_count\"],\n },\n )\n\n source_cards_60 = root / \"sources/v0.5/source_cards_60.jsonl\"\n source_dataset_60 = root / \"datasets/v0.5/source_backed_60.jsonl\"\n source_foundry_60 = artifacts / \"releases/foundry-compatible/aml_v0_5_source_backed_60_foundry.jsonl\"\n source_bundle_60 = artifacts / \"releases/foundry-compatible/aml_context_lifecycle_0.5.0_source_backed_60_bundle_000001\"\n generated_cards = generate_source_cards(60, source_cards_60)\n curated_60 = curate_source_cards(source_cards_60, source_dataset_60)\n source_export_60 = export_foundry_records(source_dataset_60, source_foundry_60)\n source_bundle_result_60 = build_foundry_bundle(source_foundry_60, source_bundle_60)\n source_bundle_verify_60 = verify_foundry_bundle(source_bundle_60)\n add(\n \"source_backed_60_curate_export_bundle\",\n len(generated_cards) == 60\n and curated_60[\"record_count\"] == 60\n and source_export_60[\"quality\"][\"passed\"]\n and source_bundle_result_60[\"quality\"][\"passed\"]\n and source_bundle_verify_60[\"passed\"],\n {\n \"dataset\": str(source_dataset_60),\n \"bundle\": str(source_bundle_60),\n \"record_count\": curated_60[\"record_count\"],\n },\n )\n\n promotion_manifest = artifacts / \"releases/promotions/aml_context_lifecycle_0.5.0_source_backed_60.promotion.json\"\n from .promotion import promote_bundle, verify_promotion_manifest\n\n promotion = promote_bundle(\n dataset_path=source_dataset_60,\n bundle_dir=source_bundle_60,\n foundry_records=source_foundry_60,\n output_manifest=promotion_manifest,\n router=\"keyword\",\n require_audit=False,\n work_dir=root,\n )\n promotion_verify = verify_promotion_manifest(promotion_manifest)\n add(\n \"promotion_gate_executes\",\n promotion[\"promoted\"] and promotion_verify[\"passed\"],\n {\n \"manifest\": str(promotion_manifest),\n \"promoted\": promotion[\"promoted\"],\n \"verify\": promotion_verify,\n },\n )\n\n review_manifest = artifacts / \"releases/reviews/aml_context_lifecycle_0.5.0_source_backed_60.review.json\"\n release_index = artifacts / \"releases/RELEASE_INDEX.json\"\n from .release import build_release_index, review_promotion, verify_release_index, verify_review_manifest\n\n review = review_promotion(\n manifest_path=promotion_manifest,\n reviewer=\"local-audit\",\n decision=\"approved\",\n notes=\"Audit-created approval for verified private local bundle.\",\n output_path=review_manifest,\n )\n review_verify = verify_review_manifest(review_manifest)\n index = build_release_index(\n promotions_dir=artifacts / \"releases/promotions\",\n reviews_dir=artifacts / \"releases/reviews\",\n output_path=release_index,\n )\n index_verify = verify_release_index(release_index)\n add(\n \"review_and_release_index_executes\",\n review[\"decision\"] == \"approved\" and review_verify[\"passed\"] and index_verify[\"passed\"],\n {\n \"review\": str(review_manifest),\n \"review_verify\": review_verify,\n \"index\": str(release_index),\n \"promotion_count\": len(index[\"promotions\"]),\n \"review_count\": len(index[\"reviews\"]),\n \"index_verify\": index_verify,\n },\n )\n\n kernel_events = root / \"events/product_stream/kernel_events.jsonl\"\n kernel_events.parent.mkdir(parents=True, exist_ok=True)\n product_events = [\n {\n \"event_id\": \"kernel-dataset-001\",\n \"text\": \"High value private dataset source for Foundry-compatible release bundles, provenance hashes, quality gates, and marketplace packaging.\",\n \"source_path\": str(root / \"README.md\"),\n \"tags\": [\"dataset\", \"foundry\", \"private\"],\n },\n {\n \"event_id\": \"kernel-eval-001\",\n \"text\": \"High value eval harness source for local audit scoring, promotion gates, release review, and hash verification.\",\n \"source_path\": str(root / \"BENCHMARK_CARD.md\"),\n \"tags\": [\"eval\", \"audit\", \"quality\"],\n },\n {\n \"event_id\": \"kernel-benchmark-001\",\n \"text\": \"Medium value benchmark source for router comparison, lifecycle apoptosis replacement, event bus replay, and regression checks.\",\n \"source_path\": str(root / \"DATASET_CARD.md\"),\n \"tags\": [\"benchmark\", \"router\", \"event bus\"],\n },\n ]\n with kernel_events.open(\"w\", encoding=\"utf-8\") as handle:\n import json\n\n for event in product_events:\n handle.write(json.dumps(event, sort_keys=True))\n handle.write(\"\\n\")\n from .product_factory import build_candidate_from_events, run_event_stream, verify_manifest_lock, verify_stream_state\n\n product = build_candidate_from_events(\n events_path=kernel_events,\n output_root=root / \"products\",\n candidate_id=\"aml_kernel_stream_audit\",\n reviewer=\"local-audit\",\n )\n lock_verify = verify_manifest_lock(product[\"manifest_lock\"])\n add(\n \"kernel_event_product_factory_executes\",\n product[\"passed\"] and product[\"accepted_event_count\"] == 3 and lock_verify[\"passed\"],\n {\n \"events\": str(kernel_events),\n \"candidate_dir\": product[\"candidate_dir\"],\n \"product_mix\": product[\"product_mix\"],\n \"manifest_lock\": product[\"manifest_lock\"],\n \"lock_verify\": lock_verify,\n },\n )\n\n stream_root = artifacts / \"products/autonomous-audit-operational\"\n autonomous = run_event_stream(\n events_path=kernel_events,\n output_root=stream_root,\n state_path=stream_root / \"STREAM_STATE.json\",\n batch_size=2,\n reviewer=\"local-audit\",\n iterations=2,\n poll_seconds=0,\n )\n state_verify = verify_stream_state(stream_root / \"STREAM_STATE.json\")\n from .node_ops import node_health, package_product, verify_package, write_release_policy\n from .release import build_release_index\n\n policy = write_release_policy(stream_root / \"PRIVATE_RELEASE_POLICY.json\")\n build_release_index(\n promotions_dir=stream_root / \"promotions\",\n reviews_dir=stream_root / \"reviews\",\n output_path=stream_root / \"RELEASE_INDEX.json\",\n )\n health = node_health(output_root=stream_root, state_path=stream_root / \"STREAM_STATE.json\", inbox=kernel_events)\n latest_candidate = stream_root / \"aml_stream_000001\"\n package = package_product(candidate_dir=latest_candidate, output_dir=artifacts / \"packages/audit\")\n package_verify = verify_package(package[\"manifest\"])\n add(\n \"autonomous_product_stream_executes\",\n autonomous[\"passed\"]\n and state_verify[\"passed\"]\n and state_verify[\"processed_event_count\"] >= 3\n and state_verify[\"candidate_count\"] >= 2,\n {\n \"stream_root\": str(stream_root),\n \"state\": str(stream_root / \"STREAM_STATE.json\"),\n \"candidates_created\": autonomous[\"candidates_created\"],\n \"state_verify\": state_verify,\n },\n )\n add(\n \"node_health_policy_package_executes\",\n health[\"passed\"] and policy[\"external_upload_allowed\"] is False and package_verify[\"passed\"],\n {\n \"health\": health,\n \"policy\": policy[\"path\"],\n \"package\": package[\"package\"],\n \"package_verify\": package_verify,\n },\n )\n\n planner_events = root / \"events/product_stream/planner_events.jsonl\"\n planner_event_rows = [\n {\n \"event_id\": \"planner-privacy-alpha\",\n \"text\": \"High value privacy provenance eval dataset release alpha source for quality gates.\",\n \"source_path\": str(root / \"README.md\"),\n \"tags\": [\"privacy\", \"provenance\", \"eval\", \"alpha\"],\n },\n {\n \"event_id\": \"planner-privacy-bravo\",\n \"text\": \"High value privacy provenance eval dataset release bravo source for quality gates.\",\n \"source_path\": str(root / \"BENCHMARK_CARD.md\"),\n \"tags\": [\"privacy\", \"provenance\", \"eval\", \"bravo\"],\n },\n {\n \"event_id\": \"planner-privacy-charlie\",\n \"text\": \"High value privacy provenance eval dataset release charlie source for quality gates.\",\n \"source_path\": str(root / \"DATASET_CARD.md\"),\n \"tags\": [\"privacy\", \"provenance\", \"eval\", \"charlie\"],\n },\n ]\n with planner_events.open(\"w\", encoding=\"utf-8\") as handle:\n import json\n\n for event in planner_event_rows:\n handle.write(json.dumps(event, sort_keys=True))\n handle.write(\"\\n\")\n from .product_planner import planner_health, run_product_node, verify_planner_state\n\n planner_root = artifacts / \"products/autonomous-commercial-v2-audit\"\n planner = run_product_node(\n events_path=planner_events,\n output_root=planner_root,\n state_path=planner_root / \"PRODUCT_PLANNER_STATE.json\",\n target_size=\"micro\",\n target_count=2,\n min_source_diversity=2,\n iterations=1,\n poll_seconds=0,\n dedupe_threshold=1.0,\n )\n planner_verify = verify_planner_state(planner_root / \"PRODUCT_PLANNER_STATE.json\")\n planner_health_result = planner_health(\n output_root=planner_root,\n state_path=planner_root / \"PRODUCT_PLANNER_STATE.json\",\n )\n add(\n \"autonomous_product_planner_executes\",\n planner[\"passed\"]\n and planner_verify[\"passed\"]\n and planner_verify[\"release_count\"] >= 1\n and planner_health_result[\"passed\"],\n {\n \"planner_root\": str(planner_root),\n \"state\": str(planner_root / \"PRODUCT_PLANNER_STATE.json\"),\n \"releases_created\": planner[\"releases_created\"],\n \"planner_verify\": planner_verify,\n \"planner_health\": planner_health_result,\n },\n )\n\n try:\n return {\n \"audit\": \"aml_local_paths\",\n \"passed\": all(check[\"passed\"] for check in checks),\n \"checks\": checks,\n }\n finally:\n if lock_fd is not None:\n os.close(lock_fd)\n try:\n lock_path.unlink()\n except FileNotFoundError:\n pass","instruction":"Explain the role of `def audit_local_paths(work_dir: str | Path='.') -> dict[str, Any]` in Primitive Foundry.","output":"`audit_local_paths` is a function in `primitive_foundry.audit`. It belongs to the privacy, release, marketplace, commercial, bus, planner, dataset, router, benchmark, source_card, product_factory area of Primitive Foundry.","source_id":"primitive_foundry.audit.audit_local_paths","task":"python_symbol_explanation"} {"id":"primitive_foundry.audit.main::explain","input":"Module: primitive_foundry.audit\nDomains: foundry\nSource path: primitive_foundry/audit.py\n\ndef main() -> None:\n result = audit_local_paths(\".\")\n print(json.dumps(result, indent=2, sort_keys=True))\n if not result[\"passed\"]:\n raise SystemExit(1)","instruction":"Explain the role of `def main() -> None` in Primitive Foundry.","output":"`main` is a function in `primitive_foundry.audit`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.audit.main","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.write_aws_data_exchange_package::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: release, dataset, benchmark, compliance, atomic_write\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef write_aws_data_exchange_package(\n *,\n release_dir: str | Path,\n output_dir: str | Path | None = None,\n product_title: str | None = None,\n price_usd: int = 49,\n duration_days: int = 365,\n support_contact: str = ACCOUNT_PLACEHOLDER,\n refund_policy: str = DEFAULT_REFUND_POLICY,\n subscription_verification: bool = True,\n provider_account_ready: bool = False,\n) -> dict[str, Any]:\n release = Path(release_dir)\n package_dir = Path(output_dir) if output_dir else release / \"aws_data_exchange\"\n package_dir.mkdir(parents=True, exist_ok=True)\n upload_dir = package_dir / \"upload\" / \"assets\"\n upload_dir.mkdir(parents=True, exist_ok=True)\n\n verified = verify_aws_release_inputs(release)\n if not verified[\"artifact_ready\"]:\n result = {\n \"passed\": False,\n \"artifact_ready\": False,\n \"aws_publish_ready\": False,\n \"package_dir\": str(package_dir),\n \"failures\": verified[\"failures\"],\n }\n atomic_write_json(package_dir / \"AWS_DATA_EXCHANGE_POSTING.json\", result)\n return result\n\n bundle_archive = upload_dir / f\"{release.name}_bundle.tar.gz\"\n write_tar_gz(release / \"bundle\", bundle_archive, arcname=\"bundle\")\n assets = [\n {\n \"asset_name\": bundle_archive.name,\n \"asset_path\": f\"upload/assets/{bundle_archive.name}\",\n \"asset_type\": \"foundry-bundle-tar-gz\",\n \"sha256\": sha256_bytes(bundle_archive.read_bytes()),\n }\n ]\n preview = release / \"bundle\" / \"preview\"\n if preview.exists():\n preview_archive = upload_dir / f\"{release.name}_preview.tar.gz\"\n write_tar_gz(preview, preview_archive, arcname=\"preview\")\n assets.append(\n {\n \"asset_name\": preview_archive.name,\n \"asset_path\": f\"upload/assets/{preview_archive.name}\",\n \"asset_type\": \"sterilized-preview-tar-gz\",\n \"sha256\": sha256_bytes(preview_archive.read_bytes()),\n }\n )\n\n schema = read_json(release / \"bundle\" / \"SCHEMA.json\")\n buyer_manifest = read_json(release / \"bundle\" / \"BUYER_MANIFEST.json\")\n promotion = read_json(verified[\"promotion_manifest\"]) if verified[\"promotion_manifest\"] else {}\n review = read_json(verified[\"review_manifest\"]) if verified[\"review_manifest\"] else {}\n release_id = release.name\n title = product_title or title_for_release(schema)\n short_description = (\n \"Sterilized Foundry-compatible AI evaluation dataset with provenance hashes, \"\n \"buyer harness, preview, and local promotion evidence.\"\n )\n long_description = (\n f\"{title}\\n\\n\"\n \"This AWS Data Exchange file dataset contains a Foundry-compatible buyer bundle, \"\n \"sterilized preview, schema, data dictionary, provenance manifest, quality report, \"\n \"checksums, examples, and an executable buyer harness. Raw private source files are \"\n \"not included. Buyer records contain derived evaluation fields, source summaries, \"\n \"source hashes, provenance hashes, rubrics, and review metadata.\"\n )\n account_blockers = account_blockers_for(\n provider_account_ready=provider_account_ready,\n support_contact=support_contact,\n refund_policy=refund_policy,\n )\n listing = {\n \"manifest_type\": \"aws_data_exchange_listing_fields\",\n \"schema_version\": 1,\n \"product_title\": title,\n \"short_description\": short_description,\n \"long_description\": long_description,\n \"provider_visible_name\": ACCOUNT_PLACEHOLDER,\n \"categories\": [\"Data\", \"Machine Learning\", \"Artificial Intelligence\"],\n \"keywords\": [\"ai evaluation\", \"benchmark\", \"foundry\", \"provenance\", \"sterilized dataset\"],\n \"product_type\": \"AWS Data Exchange files dataset\",\n \"delivery_method\": \"Files\",\n \"subscription_verification_enabled\": subscription_verification,\n \"offer\": {\n \"price_usd\": price_usd,\n \"duration_days\": duration_days,\n \"refund_policy\": refund_policy,\n \"data_subscription_agreement_file\": \"DATA_SUBSCRIPTION_AGREEMENT.md\",\n },\n \"support_contact\": support_contact,\n \"compliance_claims\": {\n \"raw_sources_included\": False,\n \"personal_data_included\": False,\n \"sensitive_personal_data_included\": False,\n \"source_files_shared_with_buyer\": False,\n \"sterilized_preview_included\": preview.exists(),\n \"claims_basis\": [\n \"bundle/CHECKSUMS.sha256\",\n \"bundle/PROVENANCE_MANIFEST.json\",\n \"bundle/QUALITY_REPORT.md\",\n \"promotions/*.promotion.json\" if verified[\"promotion_manifest\"] else \"AUTONOMOUS_RELEASE.json\",\n \"reviews/*.review.json\" if verified[\"review_manifest\"] else \"LEGAL_REVIEW_PACKET.json\",\n ],\n },\n }\n upload_manifest = {\n \"manifest_type\": \"aws_data_exchange_file_dataset_upload_manifest\",\n \"schema_version\": 1,\n \"release_id\": release_id,\n \"dataset_name\": title,\n \"revision_comment\": \"Initial sterilized Foundry-compatible dataset release.\",\n \"assets\": assets,\n \"aws_console_sequence\": [\n \"Register or sign in as an AWS Data Exchange provider.\",\n \"Create a new Files data set.\",\n \"Create a revision.\",\n \"Import each file listed in assets.\",\n \"Create a product and attach the data set revision.\",\n \"Paste aws_listing_fields.json into the product and offer forms.\",\n \"Attach DATA_SUBSCRIPTION_AGREEMENT.md and REFUND_POLICY.md terms.\",\n \"Enable subscription verification if required by the listing fields.\",\n \"Review AWS publishing guidelines, then submit/publish from AWS.\",\n ],\n }\n posting = {\n \"manifest_type\": \"aws_data_exchange_posting_package\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"release_id\": release_id,\n \"artifact_ready\": True,\n \"aws_publish_ready\": not account_blockers,\n \"account_blockers\": account_blockers,\n \"bundle_verification\": public_verification_summary(verified),\n \"promotion_hash\": promotion.get(\"promotion_hash\", \"\"),\n \"review_hash\": review.get(\"review_hash\", \"\"),\n \"record_count\": schema.get(\"record_count\"),\n \"dataset_version\": schema.get(\"dataset_version\"),\n \"buyer_manifest\": buyer_manifest,\n \"files\": {\n \"listing_fields\": \"aws_listing_fields.json\",\n \"upload_manifest\": \"aws_upload_manifest.json\",\n \"dsa\": \"DATA_SUBSCRIPTION_AGREEMENT.md\",\n \"refund_policy\": \"REFUND_POLICY.md\",\n \"publish_checklist\": \"PUBLISH_CHECKLIST.md\",\n \"integrity_manifest\": \"INTEGRITY_MANIFEST.json\",\n \"assets\": [asset[\"asset_path\"] for asset in assets],\n },\n }\n integrity = {\n \"manifest_type\": \"aws_data_exchange_integrity_manifest\",\n \"release_id\": release_id,\n \"assets\": assets,\n \"source_bundle_checksum_file\": \"bundle/CHECKSUMS.sha256\",\n }\n write_package_files(package_dir, listing, upload_manifest, posting, integrity)\n verify = verify_aws_data_exchange_package(package_dir)\n return {\n **verify,\n \"package_dir\": str(package_dir),\n \"listing_fields\": str(package_dir / \"aws_listing_fields.json\"),\n \"upload_manifest\": str(package_dir / \"aws_upload_manifest.json\"),\n \"assets\": [str(package_dir / asset[\"asset_path\"]) for asset in assets],\n }","instruction":"Explain the role of `def write_aws_data_exchange_package(*, release_dir: str | Path, output_dir: str | Path | None=None, product_title: str | None=None, price_usd: int=49, duration_days: int=365, support_contact: str=ACCOUNT_PLACEHOLDER, refund_policy: str=DEFAULT_REFUND_POLICY, subscription_verification: bool=True, provider_account_ready: bool=False) -> dict[str, Any]` in Primitive Foundry.","output":"`write_aws_data_exchange_package` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the release, dataset, benchmark, compliance, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.write_aws_data_exchange_package","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.verify_aws_data_exchange_package::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: dataset, compliance\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef verify_aws_data_exchange_package(package_dir: str | Path) -> dict[str, Any]:\n package = Path(package_dir)\n failures: list[str] = []\n required = [\n \"AWS_DATA_EXCHANGE_POSTING.json\",\n \"aws_listing_fields.json\",\n \"aws_upload_manifest.json\",\n \"DATA_SUBSCRIPTION_AGREEMENT.md\",\n \"REFUND_POLICY.md\",\n \"PUBLISH_CHECKLIST.md\",\n \"INTEGRITY_MANIFEST.json\",\n ]\n for relative in required:\n if not (package / relative).exists():\n failures.append(f\"missing:{relative}\")\n if failures:\n return package_result(package, failures, artifact_ready=False, account_blockers=[])\n\n posting = read_json(package / \"AWS_DATA_EXCHANGE_POSTING.json\")\n listing = read_json(package / \"aws_listing_fields.json\")\n upload = read_json(package / \"aws_upload_manifest.json\")\n integrity = read_json(package / \"INTEGRITY_MANIFEST.json\")\n for payload, expected in (\n (posting, \"aws_data_exchange_posting_package\"),\n (listing, \"aws_data_exchange_listing_fields\"),\n (upload, \"aws_data_exchange_file_dataset_upload_manifest\"),\n (integrity, \"aws_data_exchange_integrity_manifest\"),\n ):\n if payload.get(\"manifest_type\") != expected:\n failures.append(f\"invalid_manifest_type:{expected}\")\n\n if listing.get(\"delivery_method\") != \"Files\":\n failures.append(\"listing_delivery_method_not_files\")\n if listing.get(\"subscription_verification_enabled\") is not True:\n failures.append(\"subscription_verification_not_enabled\")\n compliance = listing.get(\"compliance_claims\", {})\n for key in (\n \"raw_sources_included\",\n \"personal_data_included\",\n \"sensitive_personal_data_included\",\n \"source_files_shared_with_buyer\",\n ):\n if compliance.get(key) is not False:\n failures.append(f\"compliance_claim_not_false:{key}\")\n account_blockers = account_blockers_for(\n provider_account_ready=not bool(posting.get(\"account_blockers\")),\n support_contact=str(listing.get(\"support_contact\") or \"\"),\n refund_policy=str(listing.get(\"offer\", {}).get(\"refund_policy\") or \"\"),\n )\n\n upload_assets = upload.get(\"assets\", [])\n integrity_assets = {asset.get(\"asset_path\"): asset for asset in integrity.get(\"assets\", [])}\n if not upload_assets:\n failures.append(\"missing_upload_assets\")\n for asset in upload_assets:\n path = package / str(asset.get(\"asset_path\") or \"\")\n if not path.exists():\n failures.append(f\"missing_asset:{asset.get('asset_path')}\")\n continue\n digest = sha256_bytes(path.read_bytes())\n if asset.get(\"sha256\") != digest:\n failures.append(f\"asset_hash_mismatch:{asset.get('asset_path')}\")\n integrity_asset = integrity_assets.get(asset.get(\"asset_path\"))\n if not integrity_asset or integrity_asset.get(\"sha256\") != digest:\n failures.append(f\"integrity_hash_mismatch:{asset.get('asset_path')}\")\n\n leak_failures = scan_posting_package_for_leaks(package)\n failures.extend(leak_failures)\n return package_result(\n package,\n failures,\n artifact_ready=not failures,\n account_blockers=account_blockers,\n )","instruction":"Explain the role of `def verify_aws_data_exchange_package(package_dir: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_aws_data_exchange_package` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the dataset, compliance area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.verify_aws_data_exchange_package","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.write_package_files::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: atomic_write\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef write_package_files(\n package_dir: Path,\n listing: dict[str, Any],\n upload_manifest: dict[str, Any],\n posting: dict[str, Any],\n integrity: dict[str, Any],\n) -> None:\n atomic_write_json(package_dir / \"aws_listing_fields.json\", listing)\n atomic_write_json(package_dir / \"aws_upload_manifest.json\", upload_manifest)\n atomic_write_json(package_dir / \"INTEGRITY_MANIFEST.json\", integrity)\n atomic_write_json(package_dir / \"AWS_DATA_EXCHANGE_POSTING.json\", posting)\n atomic_write_text(package_dir / \"DATA_SUBSCRIPTION_AGREEMENT.md\", render_dsa(listing))\n atomic_write_text(package_dir / \"REFUND_POLICY.md\", f\"# Refund Policy\\n\\n{listing['offer']['refund_policy']}\\n\")\n atomic_write_text(package_dir / \"PUBLISH_CHECKLIST.md\", render_publish_checklist(listing, posting, upload_manifest))","instruction":"Explain the role of `def write_package_files(package_dir: Path, listing: dict[str, Any], upload_manifest: dict[str, Any], posting: dict[str, Any], integrity: dict[str, Any]) -> None` in Primitive Foundry.","output":"`write_package_files` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.write_package_files","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.render_dsa::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: source_card\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef render_dsa(listing: dict[str, Any]) -> str:\n return (\n f\"# Data Subscription Agreement: {listing['product_title']}\\n\\n\"\n f\"{DEFAULT_DSA_TERMS}\\n\\n\"\n \"## Included Data\\n\\n\"\n \"- Sterilized Foundry-compatible records and splits\\n\"\n \"- Buyer evaluation harness and examples\\n\"\n \"- Provenance hashes, source summaries, rubrics, checksums, and quality report\\n\\n\"\n \"## Excluded Data\\n\\n\"\n \"- Raw private source files\\n\"\n \"- Source-card drafts with private local paths\\n\"\n \"- Credentials or personal/sensitive personal data\\n\"\n )","instruction":"Explain the role of `def render_dsa(listing: dict[str, Any]) -> str` in Primitive Foundry.","output":"`render_dsa` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the source_card area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.render_dsa","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.render_publish_checklist::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: foundry\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef render_publish_checklist(\n listing: dict[str, Any],\n posting: dict[str, Any],\n upload_manifest: dict[str, Any],\n) -> str:\n blockers = posting.get(\"account_blockers\", [])\n blocker_text = \"\\n\".join(f\"- [ ] {item}\" for item in blockers) or \"- [x] No account blockers recorded\"\n assets = \"\\n\".join(f\"- `{asset['asset_path']}`\" for asset in upload_manifest.get(\"assets\", []))\n return (\n f\"# AWS Data Exchange Publish Checklist\\n\\n\"\n f\"Product: {listing['product_title']}\\n\\n\"\n \"## Upload Assets\\n\\n\"\n f\"{assets}\\n\\n\"\n \"## Account Fields\\n\\n\"\n f\"{blocker_text}\\n\\n\"\n \"## Console/API Steps\\n\\n\"\n + \"\\n\".join(f\"- [ ] {step}\" for step in upload_manifest.get(\"aws_console_sequence\", []))\n + \"\\n\"\n )","instruction":"Explain the role of `def render_publish_checklist(listing: dict[str, Any], posting: dict[str, Any], upload_manifest: dict[str, Any]) -> str` in Primitive Foundry.","output":"`render_publish_checklist` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.render_publish_checklist","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.package_result::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: foundry\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef package_result(\n package: Path,\n failures: list[str],\n *,\n artifact_ready: bool,\n account_blockers: list[str],\n) -> dict[str, Any]:\n return {\n \"passed\": not failures,\n \"artifact_ready\": artifact_ready,\n \"aws_publish_ready\": artifact_ready and not account_blockers and not failures,\n \"account_blockers\": account_blockers,\n \"package_dir\": str(package),\n \"failures\": failures,\n }","instruction":"Explain the role of `def package_result(package: Path, failures: list[str], *, artifact_ready: bool, account_blockers: list[str]) -> dict[str, Any]` in Primitive Foundry.","output":"`package_result` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.package_result","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.public_verification_summary::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: sterilization\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef public_verification_summary(verified: dict[str, Any]) -> dict[str, Any]:\n return {\n \"artifact_ready\": verified.get(\"artifact_ready\"),\n \"failures\": verified.get(\"failures\", []),\n \"bundle_passed\": bool(verified.get(\"bundle\", {}).get(\"passed\")),\n \"sterilization_passed\": bool(verified.get(\"sterilization\", {}).get(\"passed\")),\n \"promotion_manifest\": \"promotions/*.promotion.json\" if verified.get(\"promotion_manifest\") else \"\",\n \"review_manifest\": \"reviews/*.review.json\" if verified.get(\"review_manifest\") else \"\",\n }","instruction":"Explain the role of `def public_verification_summary(verified: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`public_verification_summary` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.public_verification_summary","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.account_blockers_for::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: foundry\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef account_blockers_for(\n *,\n provider_account_ready: bool,\n support_contact: str,\n refund_policy: str,\n) -> list[str]:\n blockers: list[str] = []\n if not provider_account_ready:\n blockers.append(\"aws_data_exchange_provider_account_not_confirmed\")\n if not support_contact or support_contact == ACCOUNT_PLACEHOLDER or \"@\" not in support_contact:\n blockers.append(\"support_contact_not_ready\")\n if not refund_policy or refund_policy == ACCOUNT_PLACEHOLDER:\n blockers.append(\"refund_policy_not_ready\")\n return blockers","instruction":"Explain the role of `def account_blockers_for(*, provider_account_ready: bool, support_contact: str, refund_policy: str) -> list[str]` in Primitive Foundry.","output":"`account_blockers_for` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.account_blockers_for","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.title_for_release::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: release, dataset\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef title_for_release(schema: dict[str, Any]) -> str:\n family = str(schema.get(\"dataset_family\") or \"foundry\").replace(\"_\", \" \").title()\n version = str(schema.get(\"dataset_version\") or \"1.0.0\")\n return f\"Primitive Foundry {family} Evaluation Dataset v{version}\"","instruction":"Explain the role of `def title_for_release(schema: dict[str, Any]) -> str` in Primitive Foundry.","output":"`title_for_release` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the release, dataset area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.title_for_release","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.first_file::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: foundry\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef first_file(directory: Path, pattern: str) -> Path | None:\n if not directory.exists():\n return None\n return next(iter(sorted(directory.glob(pattern))), None)","instruction":"Explain the role of `def first_file(directory: Path, pattern: str) -> Path | None` in Primitive Foundry.","output":"`first_file` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.first_file","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.read_json::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: foundry\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef read_json(path: str | Path) -> dict[str, Any]:\n return json.loads(Path(path).read_text(encoding=\"utf-8\"))","instruction":"Explain the role of `def read_json(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`read_json` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.read_json","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.write_tar_gz::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: foundry\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef write_tar_gz(source: Path, target: Path, *, arcname: str) -> None:\n write_deterministic_tar_gz(target, [(source, arcname)])","instruction":"Explain the role of `def write_tar_gz(source: Path, target: Path, *, arcname: str) -> None` in Primitive Foundry.","output":"`write_tar_gz` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.write_tar_gz","task":"python_symbol_explanation"} {"id":"primitive_foundry.aws_data_exchange.scan_posting_package_for_leaks::explain","input":"Module: primitive_foundry.aws_data_exchange\nDomains: foundry\nSource path: primitive_foundry/aws_data_exchange.py\n\ndef scan_posting_package_for_leaks(package: Path) -> list[str]:\n failures: list[str] = []\n forbidden = {\n \"absolute_local_path\": re.compile(r\"/(home|tmp|Users|var|etc)/\"),\n \"source_path\": re.compile(r'\"source_path\"\\s*:'),\n \"stale_eda\": re.compile(r\"eda-platform|/eda/|\\\\beda\\\\b\", re.IGNORECASE),\n \"secret_marker\": re.compile(r\"(sk-[A-Za-z0-9]|api[_-]?key|secret|password|token)\", re.IGNORECASE),\n }\n for path in sorted(item for item in package.rglob(\"*\") if item.is_file()):\n if path.suffix in {\".gz\", \".tar\"}:\n continue\n text = path.read_text(encoding=\"utf-8\")\n for name, pattern in forbidden.items():\n if pattern.search(text):\n failures.append(f\"posting_leak:{name}:{path.relative_to(package)}\")\n return failures","instruction":"Explain the role of `def scan_posting_package_for_leaks(package: Path) -> list[str]` in Primitive Foundry.","output":"`scan_posting_package_for_leaks` is a function in `primitive_foundry.aws_data_exchange`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.aws_data_exchange.scan_posting_package_for_leaks","task":"python_symbol_explanation"} {"id":"primitive_foundry.build_context.BuildContext::explain","input":"Module: primitive_foundry.build_context\nDomains: foundry\nSource path: primitive_foundry/build_context.py\n\nclass BuildContext:\n seed: int = 0\n build_time: str = \"2026-05-13T00:00:00+00:00\"\n publisher_key_id: str = \"po-2026-05-A\"\n foundry_version: str = \"0.1.0\"\n deterministic: bool = False\n\n def now(self) -> str:\n if self.deterministic:\n return self.build_time\n return datetime.now(timezone.utc).isoformat()","instruction":"Explain the role of `class BuildContext` in Primitive Foundry.","output":"`BuildContext` is a class in `primitive_foundry.build_context`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.build_context.BuildContext","task":"python_symbol_explanation"} {"id":"primitive_foundry.bus_orchestration.validate_run_request::explain","input":"Module: primitive_foundry.bus_orchestration\nDomains: bus, planner, curation\nSource path: primitive_foundry/bus_orchestration.py\n\ndef validate_run_request(payload: dict[str, Any]) -> dict[str, Any]:\n if not isinstance(payload, dict):\n raise TypeError(\"foundry run request payload must be a dictionary\")\n if str(payload.get(\"requested_action\") or \"\") != \"run-product-node\":\n raise ValueError(\"unsupported_foundry_action\")\n events_path = Path(str(payload.get(\"events_path\") or \"\")).expanduser()\n output_root = Path(str(payload.get(\"output_root\") or artifact_path(\"products\", \"autonomous\"))).expanduser()\n if not events_path.exists():\n raise ValueError(f\"events_path does not exist: {events_path}\")\n request = dict(payload)\n request[\"events_path\"] = str(events_path)\n request[\"output_root\"] = str(output_root)\n if request.get(\"state_path\"):\n request[\"state_path\"] = str(Path(str(request[\"state_path\"])).expanduser())\n else:\n request[\"state_path\"] = str(output_root / \"PRODUCT_PLANNER_STATE.json\")\n if request.get(\"standing_orders_path\"):\n request[\"standing_orders_path\"] = str(Path(str(request[\"standing_orders_path\"])).expanduser())\n if request.get(\"curation_plan_path\"):\n request[\"curation_plan_path\"] = str(Path(str(request[\"curation_plan_path\"])).expanduser())\n request[\"direct_agent_call\"] = False\n request[\"human_escalation_agent\"] = \"fin\"\n return request","instruction":"Explain the role of `def validate_run_request(payload: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`validate_run_request` is a function in `primitive_foundry.bus_orchestration`. It belongs to the bus, planner, curation area of Primitive Foundry.","source_id":"primitive_foundry.bus_orchestration.validate_run_request","task":"python_symbol_explanation"} {"id":"primitive_foundry.bus_orchestration.status_event::explain","input":"Module: primitive_foundry.bus_orchestration\nDomains: bus\nSource path: primitive_foundry/bus_orchestration.py\n\ndef status_event(event_type: str, request: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]:\n return {\n \"event_type\": event_type,\n \"source\": \"primitive_foundry.product_node\",\n \"payload\": {\n \"schema_version\": 1,\n \"requested_action\": request.get(\"requested_action\"),\n \"events_path\": request.get(\"events_path\"),\n \"output_root\": request.get(\"output_root\"),\n \"state_path\": request.get(\"state_path\"),\n \"coordinator\": request.get(\"coordinator\", \"hinge\"),\n \"human_escalation_agent\": \"fin\",\n \"direct_user_notification\": False,\n \"direct_agent_call\": False,\n \"created_at\": time.time(),\n **payload,\n },\n }","instruction":"Explain the role of `def status_event(event_type: str, request: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`status_event` is a function in `primitive_foundry.bus_orchestration`. It belongs to the bus area of Primitive Foundry.","source_id":"primitive_foundry.bus_orchestration.status_event","task":"python_symbol_explanation"} {"id":"primitive_foundry.bus_poller.PollerState::explain","input":"Module: primitive_foundry.bus_poller\nDomains: bus\nSource path: primitive_foundry/bus_poller.py\n\nclass PollerState:\n adapter: str\n inbox: str\n interval_seconds: float\n started_at: float\n last_tick: PollTickResult | None = None\n tick_count: int = 0\n error_count: int = 0\n success_count: int = 0\n history: list[dict[str, Any]] = field(default_factory=list)\n\n def snapshot(self) -> dict[str, Any]:\n return {\n \"manifest_type\": \"primitive_foundry_bus_poll_status\",\n \"schema_version\": 1,\n \"adapter\": self.adapter,\n \"inbox\": self.inbox,\n \"interval_seconds\": self.interval_seconds,\n \"started_at\": self.started_at,\n \"now\": time.time(),\n \"tick_count\": self.tick_count,\n \"success_count\": self.success_count,\n \"error_count\": self.error_count,\n \"last_tick\": self.last_tick.to_dict() if self.last_tick else None,\n \"history\": self.history[-20:],\n \"iso_started_at\": datetime.fromtimestamp(self.started_at, timezone.utc).isoformat(),\n \"iso_updated_at\": datetime.now(timezone.utc).isoformat(),\n }","instruction":"Explain the role of `class PollerState` in Primitive Foundry.","output":"`PollerState` is a class in `primitive_foundry.bus_poller`. It belongs to the bus area of Primitive Foundry.","source_id":"primitive_foundry.bus_poller.PollerState","task":"python_symbol_explanation"} {"id":"primitive_foundry.bus_poller.poll_once::explain","input":"Module: primitive_foundry.bus_poller\nDomains: bus\nSource path: primitive_foundry/bus_poller.py\n\ndef poll_once(\n *,\n adapter: str | Path,\n inbox: str | Path,\n tick: int,\n) -> PollTickResult:\n \"\"\"Perform a single bus pull tick.\n\n Wraps `import_bus_events` and converts any exception into an\n `ok=False` result rather than re-raising. This is what makes the\n surrounding loop survive NATS being briefly unavailable.\n \"\"\"\n\n started = time.time()\n result = PollTickResult(tick=tick, started_at=started, finished_at=started)\n try:\n out = import_bus_events(adapter=adapter, inbox=inbox)\n result.pulled_count = int(out.get(\"pulled_count\") or 0)\n result.imported_count = int(out.get(\"imported_count\") or 0)\n result.acked_count = int(out.get(\"acked_count\") or 0)\n result.ok = True\n except Exception as exc:\n result.ok = False\n result.error = f\"{exc.__class__.__name__}: {exc}\"\n finally:\n result.finished_at = time.time()\n return result","instruction":"Explain the role of `def poll_once(*, adapter: str | Path, inbox: str | Path, tick: int) -> PollTickResult` in Primitive Foundry.","output":"`poll_once` is a function in `primitive_foundry.bus_poller`. It belongs to the bus area of Primitive Foundry.","source_id":"primitive_foundry.bus_poller.poll_once","task":"python_symbol_explanation"} {"id":"primitive_foundry.bus_poller.poll_loop::explain","input":"Module: primitive_foundry.bus_poller\nDomains: bus, atomic_write\nSource path: primitive_foundry/bus_poller.py\n\ndef poll_loop(\n *,\n adapter: str | Path,\n inbox: str | Path,\n interval_seconds: float = DEFAULT_INTERVAL_SECONDS,\n status_path: str | Path | None = None,\n max_ticks: int | None = None,\n sleep: Callable[[float], None] = time.sleep,\n stop_predicate: Callable[[], bool] | None = None,\n) -> PollerState:\n \"\"\"Run the poller until `max_ticks` is reached or SIGINT/SIGTERM is caught.\n\n `stop_predicate` lets tests inject a deterministic stop condition.\n Status is persisted to `status_path` after every tick \u2014 Athena's\n cockpit can read this file to show poll health.\n \"\"\"\n\n state = PollerState(\n adapter=str(adapter),\n inbox=str(inbox),\n interval_seconds=float(interval_seconds),\n started_at=time.time(),\n )\n stop_flag = {\"stop\": False}\n\n def _request_stop(_signum: int = 0, _frame: Any = None) -> None:\n stop_flag[\"stop\"] = True\n\n previous_handlers: dict[int, Any] = {}\n try:\n for sig in (signal.SIGINT, signal.SIGTERM):\n try:\n previous_handlers[sig] = signal.signal(sig, _request_stop)\n except (ValueError, OSError):\n # Outside main thread or unsupported signal \u2014 fine to skip.\n pass\n\n tick = 0\n while True:\n if stop_flag[\"stop\"]:\n break\n if stop_predicate is not None and stop_predicate():\n break\n tick += 1\n result = poll_once(adapter=adapter, inbox=inbox, tick=tick)\n state.tick_count = tick\n state.last_tick = result\n if result.ok:\n state.success_count += 1\n else:\n state.error_count += 1\n state.history.append(result.to_dict())\n if status_path is not None:\n try:\n locked_atomic_write_json(status_path, state.snapshot())\n except Exception:\n # Status write failure must not kill the loop.\n pass\n if max_ticks is not None and tick >= max_ticks:\n break\n sleep(interval_seconds)\n finally:\n for sig, previous in previous_handlers.items():\n try:\n signal.signal(sig, previous)\n except (ValueError, OSError):\n pass\n return state","instruction":"Explain the role of `def poll_loop(*, adapter: str | Path, inbox: str | Path, interval_seconds: float=DEFAULT_INTERVAL_SECONDS, status_path: str | Path | None=None, max_ticks: int | None=None, sleep: Callable[[float], None]=time.sleep, stop_predicate: Callable[[], bool] | None=None) -> PollerState` in Primitive Foundry.","output":"`poll_loop` is a function in `primitive_foundry.bus_poller`. It belongs to the bus, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.bus_poller.poll_loop","task":"python_symbol_explanation"} {"id":"primitive_foundry.bus_poller.resolve_status_path::explain","input":"Module: primitive_foundry.bus_poller\nDomains: bus\nSource path: primitive_foundry/bus_poller.py\n\ndef resolve_status_path(adapter: str | Path) -> Path:\n \"\"\"Default status path lives next to the adapter manifest.\"\"\"\n\n return Path(adapter).parent / DEFAULT_STATUS_FILENAME","instruction":"Explain the role of `def resolve_status_path(adapter: str | Path) -> Path` in Primitive Foundry.","output":"`resolve_status_path` is a function in `primitive_foundry.bus_poller`. It belongs to the bus area of Primitive Foundry.","source_id":"primitive_foundry.bus_poller.resolve_status_path","task":"python_symbol_explanation"} {"id":"primitive_foundry.cells.build_seed_cells::explain","input":"Module: primitive_foundry.cells\nDomains: foundry\nSource path: primitive_foundry/cells.py\n\ndef build_seed_cells() -> dict[str, Cell]:\n cells: dict[str, Cell] = {}\n for domain_path, spec in DOMAIN_SPECS.items():\n previous_cell_id: str | None = None\n keywords = tuple(spec[\"keywords\"]) # type: ignore[arg-type]\n noun = str(spec[\"noun\"])\n for year in YEARS:\n cell_id = f\"{domain_path}.{year}\"\n status = \"active\" if year == ACTIVE_YEAR else \"stale\"\n trust_score = 0.92 if status == \"active\" else (0.44 if year == 2023 else 0.37)\n cells[cell_id] = Cell(\n cell_id=cell_id,\n domain_path=domain_path,\n valid_from=f\"{year}-01-01\",\n valid_until=f\"{year}-12-31\",\n trust_score=trust_score,\n status=status,\n keywords=keywords + (str(year), noun),\n answer_template=(\n f\"The {year} {noun} example is handled by {cell_id}.\"\n if status == \"active\"\n else f\"The {year} {noun} cell is retained for audit and replacement tests.\"\n ),\n supersedes=previous_cell_id if status == \"active\" else None,\n )\n previous_cell_id = cell_id\n return cells","instruction":"Explain the role of `def build_seed_cells() -> dict[str, Cell]` in Primitive Foundry.","output":"`build_seed_cells` is a function in `primitive_foundry.cells`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.cells.build_seed_cells","task":"python_symbol_explanation"} {"id":"primitive_foundry.cells.CellRegistry::explain","input":"Module: primitive_foundry.cells\nDomains: foundry\nSource path: primitive_foundry/cells.py\n\nclass CellRegistry:\n def __init__(self, cells: dict[str, Cell] | None = None) -> None:\n self._cells = dict(cells or SEED_CELLS)\n\n @classmethod\n def from_json(cls, path: str | Path) -> \"CellRegistry\":\n with Path(path).open(\"r\", encoding=\"utf-8\") as handle:\n payload = json.load(handle)\n cells = {}\n for item in payload[\"cells\"]:\n cell = Cell(\n cell_id=item[\"cell_id\"],\n domain_path=item[\"domain_path\"],\n valid_from=item[\"valid_from\"],\n valid_until=item.get(\"valid_until\"),\n trust_score=float(item[\"trust_score\"]),\n status=item[\"status\"],\n keywords=tuple(item[\"keywords\"]),\n answer_template=item[\"answer_template\"],\n supersedes=item.get(\"supersedes\"),\n )\n cells[cell.cell_id] = cell\n return cls(cells)\n\n def to_payload(self, registry_version: str = \"local\") -> dict[str, object]:\n return {\n \"registry_version\": registry_version,\n \"cells\": [\n {\n \"cell_id\": cell.cell_id,\n \"domain_path\": cell.domain_path,\n \"valid_from\": cell.valid_from,\n \"valid_until\": cell.valid_until,\n \"trust_score\": cell.trust_score,\n \"status\": cell.status,\n \"keywords\": list(cell.keywords),\n \"answer_template\": cell.answer_template,\n \"supersedes\": cell.supersedes,\n }\n for cell in sorted(self._cells.values(), key=lambda item: item.cell_id)\n ],\n }\n\n def all(self) -> list[Cell]:\n return list(self._cells.values())\n\n def get(self, cell_id: str) -> Cell:\n return self._cells[cell_id]\n\n def active_cells(self) -> list[Cell]:\n return [cell for cell in self._cells.values() if cell.status == \"active\"]\n\n def stale_cells(self) -> list[Cell]:\n return [cell for cell in self._cells.values() if cell.status in {\"stale\", \"retired\"}]\n\n def current_for_domain(self, domain_path: str) -> Cell:\n active = [cell for cell in self.active_cells() if cell.domain_path == domain_path]\n if len(active) != 1:\n raise ValueError(f\"Expected one active cell for {domain_path}, found {len(active)}\")\n return active[0]\n\n def replacements(self) -> dict[str, str]:\n replacements: dict[str, str] = {}\n for stale_cell in self.stale_cells():\n replacements[stale_cell.cell_id] = self.current_for_domain(stale_cell.domain_path).cell_id\n return replacements\n\n def answer(self, cell_id: str, query: str) -> CellResponse:\n cell = self.get(cell_id)\n return CellResponse(\n cell_id=cell.cell_id,\n answer=f\"{cell.answer_template} Query: {query}\",\n provenance={\n \"cell_id\": cell.cell_id,\n \"domain_path\": cell.domain_path,\n \"valid_from\": cell.valid_from,\n \"valid_until\": cell.valid_until,\n \"trust_score\": cell.trust_score,\n \"status\": cell.status,\n \"supersedes\": cell.supersedes,\n },\n )","instruction":"Explain the role of `class CellRegistry` in Primitive Foundry.","output":"`CellRegistry` is a class in `primitive_foundry.cells`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.cells.CellRegistry","task":"python_symbol_explanation"} {"id":"primitive_foundry.channel_payloads.__init__.render_all::explain","input":"Module: primitive_foundry.channel_payloads.__init__\nDomains: release, marketplace\nSource path: primitive_foundry/channel_payloads/__init__.py\n\ndef render_all(release_dir: Path) -> dict[str, str]:\n return {\n \"aws_data_exchange\": str(render_aws(release_dir)),\n \"snowflake_marketplace\": str(render_snowflake(release_dir)),\n \"databricks_marketplace\": str(render_databricks(release_dir)),\n \"huggingface_hub\": str(render_huggingface(release_dir)),\n }","instruction":"Explain the role of `def render_all(release_dir: Path) -> dict[str, str]` in Primitive Foundry.","output":"`render_all` is a function in `primitive_foundry.channel_payloads.__init__`. It belongs to the release, marketplace area of Primitive Foundry.","source_id":"primitive_foundry.channel_payloads.__init__.render_all","task":"python_symbol_explanation"} {"id":"primitive_foundry.channel_payloads.aws_data_exchange.render::explain","input":"Module: primitive_foundry.channel_payloads.aws_data_exchange\nDomains: release, marketplace, dataset\nSource path: primitive_foundry/channel_payloads/aws_data_exchange.py\n\ndef render(release_dir: Path) -> Path:\n listing = json.loads((Path(release_dir) / \"MARKETPLACE_LISTING.json\").read_text(encoding=\"utf-8\"))\n out = Path(release_dir) / \"channel_payloads\" / \"aws_data_exchange\"\n out.mkdir(parents=True, exist_ok=True)\n payload = {\n \"ChangeSet\": [\n {\n \"ChangeType\": \"CreateDataSet\",\n \"Entity\": {\"Type\": \"DataSet@1.0\"},\n \"Details\": json.dumps({\"Name\": listing[\"title\"], \"Description\": listing[\"description\"]}),\n }\n ],\n \"Catalog\": \"AWSMarketplace\",\n }\n path = out / \"catalog_changeset.json\"\n path.write_text(json.dumps(payload, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return path","instruction":"Explain the role of `def render(release_dir: Path) -> Path` in Primitive Foundry.","output":"`render` is a function in `primitive_foundry.channel_payloads.aws_data_exchange`. It belongs to the release, marketplace, dataset area of Primitive Foundry.","source_id":"primitive_foundry.channel_payloads.aws_data_exchange.render","task":"python_symbol_explanation"} {"id":"primitive_foundry.channel_payloads.databricks_marketplace.render::explain","input":"Module: primitive_foundry.channel_payloads.databricks_marketplace\nDomains: release, marketplace\nSource path: primitive_foundry/channel_payloads/databricks_marketplace.py\n\ndef render(release_dir: Path) -> Path:\n listing = json.loads((Path(release_dir) / \"MARKETPLACE_LISTING.json\").read_text(encoding=\"utf-8\"))\n out = Path(release_dir) / \"channel_payloads\" / \"databricks_marketplace\"\n out.mkdir(parents=True, exist_ok=True)\n payload = {\n \"name\": listing[\"title\"],\n \"summary\": listing[\"description\"],\n \"categories\": [\"AI\", \"Evaluation\", \"Data\"],\n \"terms_required\": True,\n \"price_usd\": listing[\"price_usd\"],\n }\n path = out / \"listing.json\"\n path.write_text(json.dumps(payload, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return path","instruction":"Explain the role of `def render(release_dir: Path) -> Path` in Primitive Foundry.","output":"`render` is a function in `primitive_foundry.channel_payloads.databricks_marketplace`. It belongs to the release, marketplace area of Primitive Foundry.","source_id":"primitive_foundry.channel_payloads.databricks_marketplace.render","task":"python_symbol_explanation"} {"id":"primitive_foundry.channel_payloads.huggingface_hub.render::explain","input":"Module: primitive_foundry.channel_payloads.huggingface_hub\nDomains: release, marketplace, license\nSource path: primitive_foundry/channel_payloads/huggingface_hub.py\n\ndef render(release_dir: Path) -> Path:\n listing = json.loads((Path(release_dir) / \"MARKETPLACE_LISTING.json\").read_text(encoding=\"utf-8\"))\n out = Path(release_dir) / \"channel_payloads\" / \"huggingface_hub\"\n out.mkdir(parents=True, exist_ok=True)\n text = (\n \"---\\n\"\n \"license: other\\n\"\n \"private: true\\n\"\n \"tags:\\n\"\n \" - evaluation\\n\"\n \" - provenance\\n\"\n \"---\\n\\n\"\n f\"# {listing['title']}\\n\\n{listing['description']}\\n\"\n )\n path = out / \"README.md\"\n path.write_text(text, encoding=\"utf-8\")\n return path","instruction":"Explain the role of `def render(release_dir: Path) -> Path` in Primitive Foundry.","output":"`render` is a function in `primitive_foundry.channel_payloads.huggingface_hub`. It belongs to the release, marketplace, license area of Primitive Foundry.","source_id":"primitive_foundry.channel_payloads.huggingface_hub.render","task":"python_symbol_explanation"} {"id":"primitive_foundry.channel_payloads.snowflake_marketplace.render::explain","input":"Module: primitive_foundry.channel_payloads.snowflake_marketplace\nDomains: release, marketplace\nSource path: primitive_foundry/channel_payloads/snowflake_marketplace.py\n\ndef render(release_dir: Path) -> Path:\n listing = json.loads((Path(release_dir) / \"MARKETPLACE_LISTING.json\").read_text(encoding=\"utf-8\"))\n out = Path(release_dir) / \"channel_payloads\" / \"snowflake_marketplace\"\n out.mkdir(parents=True, exist_ok=True)\n text = (\n f\"title: {listing['title']}\\n\"\n f\"subtitle: {listing['family']}\\n\"\n f\"description: {listing['description']}\\n\"\n f\"pricing: {listing['price_usd']} {listing['currency']}\\n\"\n )\n path = out / \"provider_listing.yaml\"\n path.write_text(text, encoding=\"utf-8\")\n return path","instruction":"Explain the role of `def render(release_dir: Path) -> Path` in Primitive Foundry.","output":"`render` is a function in `primitive_foundry.channel_payloads.snowflake_marketplace`. It belongs to the release, marketplace area of Primitive Foundry.","source_id":"primitive_foundry.channel_payloads.snowflake_marketplace.render","task":"python_symbol_explanation"} {"id":"primitive_foundry.cli.emit_result::explain","input":"Module: primitive_foundry.cli\nDomains: foundry\nSource path: primitive_foundry/cli.py\n\ndef emit_result(result: dict) -> None:\n print(json.dumps(result, indent=2))\n for key in FAILURE_KEYS:\n if key in result and result[key] is False:\n raise SystemExit(1)","instruction":"Explain the role of `def emit_result(result: dict) -> None` in Primitive Foundry.","output":"`emit_result` is a function in `primitive_foundry.cli`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.cli.emit_result","task":"python_symbol_explanation"} {"id":"primitive_foundry.cli.build_parser::explain","input":"Module: primitive_foundry.cli\nDomains: sterilization, release, marketplace, commercial, bus, planner, curation, dataset, router, benchmark, source_card\nSource path: primitive_foundry/cli.py\n\ndef build_parser() -> argparse.ArgumentParser:\n parser = argparse.ArgumentParser(prog=\"primitive-foundry\")\n subcommands = parser.add_subparsers(dest=\"command\", required=True)\n\n subcommands.add_parser(\"workflow\", help=\"Print the ordered local/private Foundry release workflow.\")\n\n run = subcommands.add_parser(\"run\", help=\"Run the local Foundry benchmark.\")\n run.add_argument(\"--dataset\", required=True, help=\"Path to Foundry JSONL dataset.\")\n run.add_argument(\"--output-dir\", default=artifact_path(\"runs\"), help=\"Directory for JSON reports.\")\n run.add_argument(\"--top-k\", type=int, default=5, help=\"Number of routed cells to score.\")\n run.add_argument(\n \"--router\",\n choices=(\"keyword\", \"hashed-embedding\", \"trained\"),\n default=\"keyword\",\n help=\"Router baseline to evaluate.\",\n )\n run.add_argument(\"--router-path\", default=None, help=\"Path to trained router model JSON.\")\n run.add_argument(\"--registry\", default=None, help=\"Path to registry snapshot JSON.\")\n run.add_argument(\"--seed\", type=int, default=0)\n run.add_argument(\"--print-json\", action=\"store_true\", help=\"Print the full report JSON.\")\n\n train_router = subcommands.add_parser(\"train-router\", help=\"Train a local centroid router.\")\n train_router.add_argument(\"--dataset\", required=True)\n train_router.add_argument(\"--output\", default=\"models/router_v0_1.json\")\n train_router.add_argument(\"--dimensions\", type=int, default=128)\n\n build_v04 = subcommands.add_parser(\"build-v04\", help=\"Build v0.4 splits and registry snapshots.\")\n build_v04.add_argument(\"--dataset-dir\", default=\"datasets/v0.4\")\n build_v04.add_argument(\"--registry-dir\", default=\"registries/v0.4\")\n\n summary = subcommands.add_parser(\"summary\", help=\"Run router comparison summary.\")\n summary.add_argument(\"--dataset\", required=True)\n summary.add_argument(\"--trained-router-path\", default=None)\n summary.add_argument(\"--top-k\", type=int, default=5)\n summary.add_argument(\"--output\", default=None)\n\n compare = subcommands.add_parser(\"compare\", help=\"Compare two Foundry JSON reports.\")\n compare.add_argument(\"before\", help=\"Earlier report JSON path.\")\n compare.add_argument(\"after\", help=\"Later report JSON path.\")\n\n events = subcommands.add_parser(\"events\", help=\"Write lifecycle events for a dataset.\")\n events.add_argument(\"--dataset\", required=True, help=\"Path to Foundry JSONL dataset.\")\n events.add_argument(\"--output\", default=\"events/aml_lifecycle_events.jsonl\")\n\n simulate = subcommands.add_parser(\"simulate\", help=\"Simulate cell apoptosis replacement.\")\n simulate.add_argument(\"--dataset\", required=True, help=\"Path to Foundry JSONL dataset.\")\n simulate.add_argument(\"--output\", default=None, help=\"Optional JSON output path.\")\n\n transition = subcommands.add_parser(\"simulate-transition\", help=\"Route apoptosis records before and after a registry swap.\")\n transition.add_argument(\"--dataset\", required=True, help=\"Path to Foundry JSONL dataset.\")\n transition.add_argument(\"--pre-registry\", required=True, help=\"Registry snapshot before replacement.\")\n transition.add_argument(\"--post-registry\", required=True, help=\"Registry snapshot after replacement.\")\n transition.add_argument(\"--router\", choices=(\"keyword\", \"hashed-embedding\"), default=\"keyword\")\n transition.add_argument(\"--output\", default=None, help=\"Optional JSON output path.\")\n\n apply_events = subcommands.add_parser(\"apply-events\", help=\"Apply lifecycle events to a registry snapshot.\")\n apply_events.add_argument(\"--registry\", required=True, help=\"Input registry snapshot JSON.\")\n apply_events.add_argument(\"--events\", required=True, help=\"Lifecycle event JSONL file.\")\n apply_events.add_argument(\"--output\", required=True, help=\"Output registry snapshot JSON.\")\n apply_events.add_argument(\"--registry-version\", default=\"event-applied\")\n\n audit = subcommands.add_parser(\"audit\", help=\"Execute local Foundry mechanism checks.\")\n audit.add_argument(\"--work-dir\", default=\".\")\n audit.add_argument(\"--output\", default=None)\n\n foundry_export = subcommands.add_parser(\"foundry-export\", help=\"Export source-backed JSONL as Foundry-compatible records.\")\n foundry_export.add_argument(\"--dataset\", required=True)\n foundry_export.add_argument(\"--output\", required=True)\n\n foundry_verify = subcommands.add_parser(\"foundry-verify\", help=\"Verify Foundry-compatible JSONL records.\")\n foundry_verify.add_argument(\"--records\", required=True)\n\n foundry_bundle = subcommands.add_parser(\"foundry-bundle\", help=\"Build a local Foundry-compatible bundle.\")\n foundry_bundle.add_argument(\"--records\", required=True)\n foundry_bundle.add_argument(\"--bundle-dir\", required=True)\n\n foundry_verify_bundle = subcommands.add_parser(\"foundry-verify-bundle\", help=\"Verify a Foundry-compatible bundle directory.\")\n foundry_verify_bundle.add_argument(\"--bundle-dir\", required=True)\n\n foundry_repair_bundle = subcommands.add_parser(\"foundry-repair-bundle\", help=\"Repair a bundle to the current executable schema.\")\n foundry_repair_bundle.add_argument(\"--bundle-dir\", required=True)\n\n curate_sources = subcommands.add_parser(\"curate-sources\", help=\"Create Foundry records from private source cards.\")\n curate_sources.add_argument(\"--cards\", required=True)\n curate_sources.add_argument(\"--output\", required=True)\n\n generate_cards = subcommands.add_parser(\"generate-source-cards\", help=\"Generate private source-card JSONL.\")\n generate_cards.add_argument(\"--count\", type=int, default=60)\n generate_cards.add_argument(\"--output\", default=\"sources/v0.5/source_cards_60.jsonl\")\n\n promote = subcommands.add_parser(\"promote\", help=\"Run release promotion gates and write a manifest.\")\n promote.add_argument(\"--dataset\", required=True)\n promote.add_argument(\"--bundle-dir\", required=True)\n promote.add_argument(\"--foundry-records\", required=True)\n promote.add_argument(\"--output\", required=True)\n promote.add_argument(\"--router\", choices=(\"keyword\", \"hashed-embedding\", \"trained\"), default=\"keyword\")\n promote.add_argument(\"--registry\", default=None)\n promote.add_argument(\"--min-pass-rate\", type=float, default=1.0)\n promote.add_argument(\"--min-top-k\", type=float, default=1.0)\n promote.add_argument(\"--skip-audit\", action=\"store_true\")\n\n verify_promotion = subcommands.add_parser(\"verify-promotion\", help=\"Verify a promotion manifest.\")\n verify_promotion.add_argument(\"--manifest\", required=True)\n\n review = subcommands.add_parser(\"review-promotion\", help=\"Create a human review manifest for a promotion.\")\n review.add_argument(\"--manifest\", required=True)\n review.add_argument(\"--reviewer\", required=True)\n review.add_argument(\"--decision\", choices=(\"approved\", \"rejected\", \"needs_changes\"), required=True)\n review.add_argument(\"--notes\", default=\"\")\n review.add_argument(\"--output\", required=True)\n\n verify_review = subcommands.add_parser(\"verify-review\", help=\"Verify a review manifest.\")\n verify_review.add_argument(\"--manifest\", required=True)\n\n release_index = subcommands.add_parser(\"release-index\", help=\"Build a release index from promotions and reviews.\")\n release_index.add_argument(\"--promotions-dir\", default=artifact_path(\"releases\", \"promotions\"))\n release_index.add_argument(\"--reviews-dir\", default=artifact_path(\"releases\", \"reviews\"))\n release_index.add_argument(\"--output\", default=artifact_path(\"releases\", \"RELEASE_INDEX.json\"))\n\n verify_index = subcommands.add_parser(\"verify-release-index\", help=\"Verify a release index.\")\n verify_index.add_argument(\"--index\", required=True)\n\n build_candidate = subcommands.add_parser(\n \"build-candidate\",\n help=\"Build a private product candidate from local event-bus JSONL.\",\n )\n build_candidate.add_argument(\"--events\", required=True, help=\"Event-bus JSONL input.\")\n build_candidate.add_argument(\"--output-root\", default=artifact_path(\"products\"))\n build_candidate.add_argument(\"--candidate-id\", default=None)\n build_candidate.add_argument(\"--min-value-score\", type=float, default=0.62)\n build_candidate.add_argument(\"--reviewer\", default=\"local-owner\")\n build_candidate.add_argument(\"--max-records\", type=int, default=None)\n build_candidate.add_argument(\"--min-records\", type=int, default=1)\n build_candidate.add_argument(\"--min-source-diversity\", type=int, default=1)\n build_candidate.add_argument(\"--require-product-kind\", action=\"append\", default=[])\n build_candidate.add_argument(\"--classifier\", choices=(\"deterministic\", \"hashed\"), default=\"deterministic\")\n build_candidate.add_argument(\"--no-approve\", action=\"store_true\")\n\n stream_products = subcommands.add_parser(\n \"stream-products\",\n help=\"Consume local event-bus JSONL and append sale-ready product artifacts.\",\n )\n stream_products.add_argument(\"--events\", required=True, help=\"Event-bus JSONL input.\")\n stream_products.add_argument(\"--output-root\", default=artifact_path(\"products\"))\n stream_products.add_argument(\"--candidate-id\", default=None)\n stream_products.add_argument(\"--min-value-score\", type=float, default=0.62)\n stream_products.add_argument(\"--reviewer\", default=\"local-owner\")\n stream_products.add_argument(\"--max-records\", type=int, default=None)\n stream_products.add_argument(\"--min-records\", type=int, default=1)\n stream_products.add_argument(\"--min-source-diversity\", type=int, default=1)\n stream_products.add_argument(\"--require-product-kind\", action=\"append\", default=[])\n stream_products.add_argument(\"--classifier\", choices=(\"deterministic\", \"hashed\"), default=\"deterministic\")\n stream_products.add_argument(\"--no-approve\", action=\"store_true\")\n\n verify_lock = subcommands.add_parser(\"verify-lock\", help=\"Verify a product MANIFEST.lock.\")\n verify_lock.add_argument(\"--manifest-lock\", required=True)\n\n run_stream = subcommands.add_parser(\n \"run-stream\",\n help=\"Run the autonomous local product stream with cursor/state tracking.\",\n )\n run_stream.add_argument(\"--events\", required=True, help=\"Append-only event-bus JSONL input.\")\n run_stream.add_argument(\"--output-root\", default=artifact_path(\"products\", \"node-stream-operational\"))\n run_stream.add_argument(\"--state\", default=None)\n run_stream.add_argument(\"--batch-size\", type=int, default=25)\n run_stream.add_argument(\"--min-value-score\", type=float, default=0.62)\n run_stream.add_argument(\"--reviewer\", default=\"local-owner\")\n run_stream.add_argument(\"--iterations\", type=int, default=1)\n run_stream.add_argument(\"--poll-seconds\", type=float, default=5.0)\n run_stream.add_argument(\"--min-records\", type=int, default=1)\n run_stream.add_argument(\"--min-source-diversity\", type=int, default=1)\n run_stream.add_argument(\"--require-product-kind\", action=\"append\", default=[])\n run_stream.add_argument(\"--dedupe-threshold\", type=float, default=0.92)\n run_stream.add_argument(\"--classifier\", choices=(\"deterministic\", \"hashed\"), default=\"deterministic\")\n run_stream.add_argument(\"--no-approve\", action=\"store_true\")\n\n verify_stream = subcommands.add_parser(\"verify-stream-state\", help=\"Verify autonomous stream state.\")\n verify_stream.add_argument(\"--state\", required=True)\n\n append_event = subcommands.add_parser(\"append-event\", help=\"Append one validated event to a local inbox JSONL.\")\n append_event.add_argument(\"--inbox\", default=\"events/inbox/kernel_events.jsonl\")\n append_event.add_argument(\"--text\", required=True)\n append_event.add_argument(\"--source-path\", required=True)\n append_event.add_argument(\"--event-id\", default=None)\n append_event.add_argument(\"--source-id\", default=None)\n append_event.add_argument(\"--tag\", action=\"append\", default=[])\n\n validate_events = subcommands.add_parser(\"validate-inbox\", help=\"Validate an event inbox JSONL.\")\n validate_events.add_argument(\"--inbox\", default=\"events/inbox/kernel_events.jsonl\")\n\n health = subcommands.add_parser(\"node-health\", help=\"Verify node stream health and product ledgers.\")\n health.add_argument(\"--output-root\", default=artifact_path(\"products\", \"node-stream-operational\"))\n health.add_argument(\"--state\", default=None)\n health.add_argument(\"--inbox\", default=None)\n health.add_argument(\"--run-audit\", action=\"store_true\")\n health.add_argument(\"--work-dir\", default=\".\")\n health.add_argument(\"--allow-missing-policy\", action=\"store_true\")\n\n verify_catalog = subcommands.add_parser(\"verify-product-catalog\", help=\"Verify PRODUCT_CATALOG.json.\")\n verify_catalog.add_argument(\"--catalog\", default=artifact_path(\"products\", \"PRODUCT_CATALOG.json\"))\n\n package = subcommands.add_parser(\"package-product\", help=\"Create a private product tarball without raw sources.\")\n package.add_argument(\"--candidate-dir\", required=True)\n package.add_argument(\"--output-dir\", default=artifact_path(\"packages\"))\n\n verify_pkg = subcommands.add_parser(\"verify-package\", help=\"Verify a private product package manifest/tarball.\")\n verify_pkg.add_argument(\"--manifest\", required=True)\n\n repair_lock = subcommands.add_parser(\"repair-product-lock\", help=\"Recompute artifact hashes in a product MANIFEST.lock.\")\n repair_lock.add_argument(\"--candidate-dir\", required=True)\n\n service = subcommands.add_parser(\"write-service-files\", help=\"Write local runner and systemd user service files.\")\n service.add_argument(\"--output-dir\", default=\"node\")\n service.add_argument(\"--repo-dir\", default=\".\")\n service.add_argument(\"--events\", default=\"events/inbox/kernel_events.jsonl\")\n service.add_argument(\"--output-root\", default=artifact_path(\"products\", \"node-stream-operational\"))\n service.add_argument(\"--state\", default=artifact_path(\"products\", \"node-stream-operational\", \"STREAM_STATE.json\"))\n service.add_argument(\"--poll-seconds\", type=float, default=5.0)\n service.add_argument(\"--batch-size\", type=int, default=25)\n\n install_service = subcommands.add_parser(\"install-node-service\", help=\"Install node service files into a user systemd directory.\")\n install_service.add_argument(\"--service-file\", default=\"node/primitive-foundry-node.service\")\n install_service.add_argument(\"--runner-file\", default=\"node/run-primitive-foundry-node.sh\")\n install_service.add_argument(\"--systemd-dir\", default=\"~/.config/systemd/user\")\n\n uninstall_service = subcommands.add_parser(\"uninstall-node-service\", help=\"Remove node service files from a user systemd directory.\")\n uninstall_service.add_argument(\"--systemd-dir\", default=\"~/.config/systemd/user\")\n\n policy = subcommands.add_parser(\"write-release-policy\", help=\"Write a private local release policy manifest.\")\n policy.add_argument(\"--path\", default=artifact_path(\"products\", \"node-stream-operational\", \"PRIVATE_RELEASE_POLICY.json\"))\n\n verify_policy = subcommands.add_parser(\"verify-release-policy\", help=\"Verify a private local release policy manifest.\")\n verify_policy.add_argument(\"--path\", required=True)\n\n import_bus = subcommands.add_parser(\"import-bus-events\", help=\"Import events through a local bus adapter manifest.\")\n import_bus.add_argument(\"--adapter\", required=True)\n import_bus.add_argument(\"--inbox\", default=\"events/inbox/kernel_events.jsonl\")\n\n write_kernel_adapter = subcommands.add_parser(\n \"write-kernel-bus-adapter\",\n help=\"Write a local NATS JetStream adapter manifest for Context Primitive kernel events.\",\n )\n write_kernel_adapter.add_argument(\"--output\", default=\"events/inbox/kernel_nats_adapter.json\")\n write_kernel_adapter.add_argument(\"--event-bus-root\", default=\"/home/[USER] is the context primitive core ecosystem with tennets/infra/event-bus\")\n write_kernel_adapter.add_argument(\"--nats-url\", default=\"nats://127.0.0.1:4222\")\n write_kernel_adapter.add_argument(\"--stream\", default=\"PRIMITIVE\")\n write_kernel_adapter.add_argument(\"--durable\", default=\"primitive-foundry-importer\")\n write_kernel_adapter.add_argument(\"--batch\", type=int, default=25)\n write_kernel_adapter.add_argument(\"--subject\", action=\"append\", default=[])\n write_kernel_adapter.add_argument(\"--no-ack\", action=\"store_true\")\n\n bus_poll = subcommands.add_parser(\n \"bus-poll\",\n help=\"Continuously pull kernel NATS events into the foundry inbox.\",\n )\n bus_poll.add_argument(\"--adapter\", default=\"events/inbox/kernel_nats_adapter.json\")\n bus_poll.add_argument(\"--inbox\", default=\"events/inbox/kernel_events.jsonl\")\n bus_poll.add_argument(\"--interval\", type=float, default=10.0,\n help=\"Seconds between bus pulls (default: 10)\")\n bus_poll.add_argument(\"--status-path\", default=None,\n help=\"Override status file path. Defaults to /bus_poll_status.json\")\n bus_poll.add_argument(\"--max-ticks\", type=int, default=None,\n help=\"Stop after N ticks (default: run until SIGINT/SIGTERM)\")\n\n kernel_node = subcommands.add_parser(\n \"run-kernel-bus-product-node\",\n help=\"Import kernel NATS events into the private inbox, then run the autonomous product node.\",\n )\n kernel_node.add_argument(\"--adapter\", default=\"events/inbox/kernel_nats_adapter.json\")\n kernel_node.add_argument(\"--inbox\", default=\"events/inbox/kernel_events.jsonl\")\n kernel_node.add_argument(\"--output-root\", default=artifact_path(\"products\", \"autonomous\"))\n kernel_node.add_argument(\"--state\", default=None)\n kernel_node.add_argument(\"--target-size\", choices=tuple(STANDARD_PRODUCT_SIZES), default=\"standard\")\n kernel_node.add_argument(\"--target-count\", type=int, default=None)\n kernel_node.add_argument(\"--min-value-score\", type=float, default=0.62)\n kernel_node.add_argument(\"--min-source-diversity\", type=int, default=3)\n kernel_node.add_argument(\"--classifier\", choices=(\"deterministic\", \"hashed\"), default=\"deterministic\")\n kernel_node.add_argument(\"--dedupe-threshold\", type=float, default=0.92)\n kernel_node.add_argument(\"--reviewer\", default=\"local-autonomous-reviewer\")\n kernel_node.add_argument(\"--iterations\", type=int, default=1)\n kernel_node.add_argument(\"--poll-seconds\", type=float, default=5.0)\n kernel_node.add_argument(\"--delivery-shape\", action=\"append\", default=[\"tar_gz\"])\n kernel_node.add_argument(\"--standing-orders\", default=None)\n kernel_node.add_argument(\"--curation-plan\", default=None)\n\n product_node = subcommands.add_parser(\n \"run-product-node\",\n help=\"Autonomously queue event-bus records into standardized sale-grade product releases.\",\n )\n product_node.add_argument(\"--events\", required=True)\n product_node.add_argument(\"--output-root\", default=artifact_path(\"products\", \"autonomous\"))\n product_node.add_argument(\"--state\", default=None)\n product_node.add_argument(\"--target-size\", choices=tuple(STANDARD_PRODUCT_SIZES), default=\"standard\")\n product_node.add_argument(\"--target-count\", type=int, default=None)\n product_node.add_argument(\"--min-value-score\", type=float, default=0.62)\n product_node.add_argument(\"--min-source-diversity\", type=int, default=3)\n product_node.add_argument(\"--classifier\", choices=(\"deterministic\", \"hashed\"), default=\"deterministic\")\n product_node.add_argument(\"--dedupe-threshold\", type=float, default=0.92)\n product_node.add_argument(\"--reviewer\", default=\"local-autonomous-reviewer\")\n product_node.add_argument(\"--iterations\", type=int, default=1)\n product_node.add_argument(\"--poll-seconds\", type=float, default=5.0)\n product_node.add_argument(\"--delivery-shape\", action=\"append\", default=[\"tar_gz\"])\n product_node.add_argument(\"--standing-orders\", default=None)\n product_node.add_argument(\"--curation-plan\", default=None)\n\n curation_plan = subcommands.add_parser(\n \"plan-curation\",\n help=\"Score local bus events against Foundry standing orders and emit a sale-focused curation plan.\",\n )\n curation_plan.add_argument(\"--events\", required=True)\n curation_plan.add_argument(\"--standing-orders\", default=None)\n curation_plan.add_argument(\"--output\", default=None)\n curation_plan.add_argument(\"--min-value-score\", type=float, default=0.62)\n curation_plan.add_argument(\"--classifier\", choices=(\"deterministic\", \"hashed\"), default=\"deterministic\")\n curation_plan.add_argument(\"--max-opportunities\", type=int, default=12)\n\n orders = subcommands.add_parser(\"write-standing-orders\", help=\"Write a local Foundry standing-order manifest.\")\n orders.add_argument(\"--output\", required=True)\n orders.add_argument(\"--order-id\", required=True)\n orders.add_argument(\"--priority\", type=int, default=80)\n orders.add_argument(\"--focus-family\", action=\"append\", default=[])\n orders.add_argument(\"--product-kind\", action=\"append\", default=[])\n orders.add_argument(\"--keyword\", action=\"append\", default=[])\n orders.add_argument(\"--banned-keyword\", action=\"append\", default=[])\n orders.add_argument(\"--min-value-score\", type=float, default=0.62)\n orders.add_argument(\"--target-count\", type=int, default=None)\n orders.add_argument(\"--no-complementary-bundle\", action=\"store_true\")\n orders.add_argument(\"--research-allowed\", action=\"store_true\")\n orders.add_argument(\"--notes\", default=\"\")\n\n verify_planner = subcommands.add_parser(\"verify-product-planner-state\", help=\"Verify autonomous product planner state.\")\n verify_planner.add_argument(\"--state\", required=True)\n\n verify_planner_queues_cmd = subcommands.add_parser(\"verify-product-queues\", help=\"Verify autonomous product queue files.\")\n verify_planner_queues_cmd.add_argument(\"--queues\", default=artifact_path(\"products\", \"autonomous\", \"queues\"))\n\n verify_release = subcommands.add_parser(\"verify-autonomous-release\", help=\"Verify one autonomous product release manifest.\")\n verify_release.add_argument(\"--manifest\", required=True)\n\n verify_commercial = subcommands.add_parser(\"verify-commercial-release\", help=\"Verify commercial listing, readiness, and terms.\")\n verify_commercial.add_argument(\"--release-dir\", required=True)\n\n verify_external = subcommands.add_parser(\n \"verify-external-listing\",\n help=\"Verify external marketplace listing readiness, including legal approval.\",\n )\n verify_external.add_argument(\"--release-dir\", required=True)\n\n marketplace_packets = subcommands.add_parser(\n \"write-marketplace-packets\",\n help=\"Write local marketplace account-prep drafts for a verified release.\",\n )\n marketplace_packets.add_argument(\"--release-dir\", required=True)\n marketplace_packets.add_argument(\"--output-dir\", default=None)\n\n aws_package = subcommands.add_parser(\n \"write-aws-data-exchange-package\",\n help=\"Write AWS Data Exchange file-dataset posting artifacts for a verified release.\",\n )\n aws_package.add_argument(\"--release-dir\", required=True)\n aws_package.add_argument(\"--output-dir\", default=None)\n aws_package.add_argument(\"--product-title\", default=None)\n aws_package.add_argument(\"--price-usd\", type=int, default=49)\n aws_package.add_argument(\"--duration-days\", type=int, default=365)\n aws_package.add_argument(\"--support-contact\", default=\"SET_IN_AWS_PROVIDER_ACCOUNT\")\n aws_package.add_argument(\n \"--refund-policy\",\n default=\"Refund requests are reviewed within 14 days for undelivered, corrupt, or materially misdescribed packages.\",\n )\n aws_package.add_argument(\"--no-subscription-verification\", action=\"store_true\")\n aws_package.add_argument(\"--provider-account-ready\", action=\"store_true\")\n\n aws_verify = subcommands.add_parser(\n \"verify-aws-data-exchange-package\",\n help=\"Verify AWS Data Exchange posting artifacts for leaks and required fields.\",\n )\n aws_verify.add_argument(\"--package-dir\", required=True)\n\n preview = subcommands.add_parser(\"build-preview\", help=\"Build a sterilized buyer preview for one release.\")\n preview.add_argument(\"--release-dir\", required=True)\n preview.add_argument(\"--preview-records\", type=int, default=10)\n preview.add_argument(\"--include-ground-truth\", action=\"store_true\")\n\n approve_external = subcommands.add_parser(\n \"approve-external-listing\",\n help=\"Record legal/listing approval, rebuild package, and mark a release externally listable.\",\n )\n approve_external.add_argument(\"--release-dir\", required=True)\n approve_external.add_argument(\"--reviewer\", required=True)\n approve_external.add_argument(\"--notes\", required=True)\n approve_external.add_argument(\"--support-contact\", required=True)\n approve_external.add_argument(\"--refund-policy\", required=True)\n approve_external.add_argument(\"--tax-vat-status\", required=True)\n approve_external.add_argument(\"--package-output-dir\", default=None)\n\n refresh_package = subcommands.add_parser(\n \"refresh-release-package\",\n help=\"Rebuild and reverify an existing autonomous release package without changing approval.\",\n )\n refresh_package.add_argument(\"--release-dir\", required=True)\n refresh_package.add_argument(\"--package-output-dir\", default=None)\n\n repair_release = subcommands.add_parser(\n \"repair-release-artifacts\",\n help=\"Backfill commercial artifacts and rebuild package for an unapproved autonomous release.\",\n )\n repair_release.add_argument(\"--release-dir\", required=True)\n repair_release.add_argument(\"--package-output-dir\", default=None)\n\n verify_sterile_bundle = subcommands.add_parser(\"verify-sterilized-bundle\", help=\"Verify bundle JSONL payload sterilization.\")\n verify_sterile_bundle.add_argument(\"--bundle-dir\", required=True)\n\n verify_sterile_jsonl = subcommands.add_parser(\"verify-sterilized-jsonl\", help=\"Verify one JSONL payload is sterilized.\")\n verify_sterile_jsonl.add_argument(\"--path\", required=True)\n\n planner_health_cmd = subcommands.add_parser(\"product-planner-health\", help=\"Verify planner state, queues, releases, and packages.\")\n planner_health_cmd.add_argument(\"--output-root\", default=artifact_path(\"products\", \"autonomous\"))\n planner_health_cmd.add_argument(\"--state\", default=None)\n\n return parser","instruction":"Explain the role of `def build_parser() -> argparse.ArgumentParser` in Primitive Foundry.","output":"`build_parser` is a function in `primitive_foundry.cli`. It belongs to the sterilization, release, marketplace, commercial, bus, planner, curation, dataset, router, benchmark, source_card area of Primitive Foundry.","source_id":"primitive_foundry.cli.build_parser","task":"python_symbol_explanation"} {"id":"primitive_foundry.cli.main::explain","input":"Module: primitive_foundry.cli\nDomains: release, marketplace, commercial, bus, planner, curation, dataset, router, benchmark, source_card\nSource path: primitive_foundry/cli.py\n\ndef main() -> None:\n parser = build_parser()\n args = parser.parse_args()\n try:\n if args.command == \"workflow\":\n emit_result({\"passed\": True, **workflow_payload()})\n elif args.command == \"run\":\n runner = BenchmarkRunner(\n top_k=args.top_k,\n router_name=args.router,\n router_path=args.router_path,\n registry_path=args.registry,\n seed=args.seed,\n )\n report = runner.run_dataset(args.dataset)\n report_path = write_report(report, args.output_dir)\n if args.print_json:\n print(json.dumps(report, indent=2))\n print(\n f\"Foundry benchmark complete: {report['record_count']} records, \"\n f\"pass_rate={report['pass_rate']:.2f}, report={report_path}\"\n )\n elif args.command == \"train-router\":\n model = train_centroid_router(args.dataset, args.output, args.dimensions)\n print(f\"Trained centroid router: {len(model['cell_ids'])} cells, output={args.output}\")\n elif args.command == \"build-v04\":\n dataset_paths = build_v04_splits(args.dataset_dir)\n registry_paths = write_registry_snapshots(args.registry_dir)\n paths = list(dataset_paths.values()) + list(registry_paths.values())\n print(\"Foundry v0.4 artifacts complete: \" + \", \".join(str(path) for path in paths))\n elif args.command == \"summary\":\n result = router_summary(args.dataset, args.trained_router_path, args.top_k)\n print_summary_table(result)\n if args.output:\n output_path = write_summary(result, args.output)\n print(f\"summary={output_path}\")\n elif args.command == \"compare\":\n comparison = compare_reports(args.before, args.after)\n print(json.dumps(comparison, indent=2))\n elif args.command == \"events\":\n event_list = build_lifecycle_events(args.dataset)\n output_path = write_lifecycle_events(event_list, args.output)\n print(f\"Foundry lifecycle events complete: {len(event_list)} events, output={output_path}\")\n elif args.command == \"simulate\":\n simulation = simulate_replacement(args.dataset)\n payload = json.dumps(simulation, indent=2)\n if args.output:\n output_path = Path(args.output)\n output_path.parent.mkdir(parents=True, exist_ok=True)\n with output_path.open(\"w\", encoding=\"utf-8\") as handle:\n handle.write(payload)\n handle.write(\"\\n\")\n print(f\"Foundry replacement simulation complete: output={args.output}\")\n else:\n print(payload)\n elif args.command == \"simulate-transition\":\n from .lifecycle import simulate_registry_transition\n\n simulation = simulate_registry_transition(\n dataset_path=args.dataset,\n pre_registry_path=args.pre_registry,\n post_registry_path=args.post_registry,\n router_name=args.router,\n )\n payload = json.dumps(simulation, indent=2)\n if args.output:\n output_path = Path(args.output)\n output_path.parent.mkdir(parents=True, exist_ok=True)\n with output_path.open(\"w\", encoding=\"utf-8\") as handle:\n handle.write(payload)\n handle.write(\"\\n\")\n print(f\"Foundry registry transition simulation complete: output={args.output}\")\n else:\n print(payload)\n elif args.command == \"apply-events\":\n result = apply_lifecycle_events(\n registry_path=args.registry,\n events_path=args.events,\n output_path=args.output,\n registry_version=args.registry_version,\n )\n emit_result(result)\n elif args.command == \"audit\":\n result = audit_local_paths(args.work_dir)\n payload = json.dumps(result, indent=2)\n if args.output:\n output_path = Path(args.output)\n output_path.parent.mkdir(parents=True, exist_ok=True)\n output_path.write_text(payload + \"\\n\", encoding=\"utf-8\")\n print(f\"Foundry audit complete: passed={result['passed']}, output={output_path}\")\n if result.get(\"passed\") is False:\n raise SystemExit(1)\n else:\n emit_result(result)\n elif args.command == \"foundry-export\":\n result = export_foundry_records(args.dataset, args.output)\n emit_result(result)\n elif args.command == \"foundry-verify\":\n result = verify_foundry_records(args.records)\n emit_result(result)\n elif args.command == \"foundry-bundle\":\n result = build_foundry_bundle(args.records, args.bundle_dir)\n emit_result(result)\n elif args.command == \"foundry-verify-bundle\":\n result = verify_foundry_bundle(args.bundle_dir)\n emit_result(result)\n elif args.command == \"foundry-repair-bundle\":\n result = repair_foundry_bundle(args.bundle_dir)\n emit_result(result)\n elif args.command == \"curate-sources\":\n result = curate_source_cards(args.cards, args.output)\n emit_result(result)\n elif args.command == \"generate-source-cards\":\n records = generate_source_cards(args.count, args.output)\n print(f\"Wrote {len(records)} source cards to {args.output}\")\n elif args.command == \"promote\":\n result = promote_bundle(\n dataset_path=args.dataset,\n bundle_dir=args.bundle_dir,\n foundry_records=args.foundry_records,\n output_manifest=args.output,\n router=args.router,\n registry_path=args.registry,\n min_pass_rate=args.min_pass_rate,\n min_top_k=args.min_top_k,\n require_audit=not args.skip_audit,\n )\n emit_result(result)\n elif args.command == \"verify-promotion\":\n result = verify_promotion_manifest(args.manifest)\n emit_result(result)\n elif args.command == \"review-promotion\":\n result = review_promotion(\n manifest_path=args.manifest,\n reviewer=args.reviewer,\n decision=args.decision,\n notes=args.notes,\n output_path=args.output,\n )\n emit_result(result)\n elif args.command == \"verify-review\":\n result = verify_review_manifest(args.manifest)\n emit_result(result)\n elif args.command == \"release-index\":\n result = build_release_index(\n promotions_dir=args.promotions_dir,\n reviews_dir=args.reviews_dir,\n output_path=args.output,\n )\n emit_result(result)\n elif args.command == \"verify-release-index\":\n result = verify_release_index(args.index)\n emit_result(result)\n elif args.command in {\"build-candidate\", \"stream-products\"}:\n result = build_candidate_from_events(\n events_path=args.events,\n output_root=args.output_root,\n candidate_id=args.candidate_id,\n min_value_score=args.min_value_score,\n reviewer=args.reviewer,\n approve=not args.no_approve,\n max_records=args.max_records,\n min_records=args.min_records,\n min_source_diversity=args.min_source_diversity,\n require_product_kinds=tuple(args.require_product_kind),\n classifier=args.classifier,\n )\n emit_result(result)\n elif args.command == \"verify-lock\":\n result = verify_manifest_lock(args.manifest_lock)\n emit_result(result)\n elif args.command == \"run-stream\":\n result = run_event_stream(\n events_path=args.events,\n output_root=args.output_root,\n state_path=args.state,\n batch_size=args.batch_size,\n min_value_score=args.min_value_score,\n reviewer=args.reviewer,\n approve=not args.no_approve,\n iterations=args.iterations,\n poll_seconds=args.poll_seconds,\n min_records=args.min_records,\n min_source_diversity=args.min_source_diversity,\n require_product_kinds=tuple(args.require_product_kind),\n dedupe_threshold=args.dedupe_threshold,\n classifier=args.classifier,\n )\n emit_result(result)\n elif args.command == \"verify-stream-state\":\n result = verify_stream_state(args.state)\n emit_result(result)\n elif args.command == \"append-event\":\n result = append_inbox_event(\n inbox=args.inbox,\n text=args.text,\n source_path=args.source_path,\n event_id=args.event_id,\n source_id=args.source_id,\n tags=args.tag,\n )\n emit_result(result)\n elif args.command == \"validate-inbox\":\n result = validate_inbox(args.inbox)\n emit_result(result)\n elif args.command == \"node-health\":\n result = node_health(\n output_root=args.output_root,\n state_path=args.state,\n inbox=args.inbox,\n run_audit=args.run_audit,\n work_dir=args.work_dir,\n require_policy=not args.allow_missing_policy,\n )\n emit_result(result)\n elif args.command == \"verify-product-catalog\":\n result = verify_product_catalog(args.catalog)\n emit_result(result)\n elif args.command == \"package-product\":\n result = package_product(candidate_dir=args.candidate_dir, output_dir=args.output_dir)\n emit_result(result)\n elif args.command == \"verify-package\":\n result = verify_package(args.manifest)\n emit_result(result)\n elif args.command == \"repair-product-lock\":\n result = repair_product_manifest_lock(args.candidate_dir)\n emit_result(result)\n elif args.command == \"write-service-files\":\n result = write_service_files(\n output_dir=args.output_dir,\n repo_dir=args.repo_dir,\n events=args.events,\n output_root=args.output_root,\n state=args.state,\n poll_seconds=args.poll_seconds,\n batch_size=args.batch_size,\n )\n emit_result(result)\n elif args.command == \"install-node-service\":\n result = install_node_service(\n service_file=args.service_file,\n runner_file=args.runner_file,\n systemd_dir=args.systemd_dir,\n )\n emit_result(result)\n elif args.command == \"uninstall-node-service\":\n result = uninstall_node_service(systemd_dir=args.systemd_dir)\n emit_result(result)\n elif args.command == \"write-release-policy\":\n result = write_release_policy(args.path)\n emit_result(result)\n elif args.command == \"verify-release-policy\":\n result = verify_release_policy(args.path)\n emit_result(result)\n elif args.command == \"import-bus-events\":\n result = import_bus_events(adapter=args.adapter, inbox=args.inbox)\n emit_result(result)\n elif args.command == \"write-kernel-bus-adapter\":\n output = Path(args.output)\n output.parent.mkdir(parents=True, exist_ok=True)\n payload = {\n \"adapter_type\": \"nats_jetstream\",\n \"event_bus_root\": args.event_bus_root,\n \"nats_url\": args.nats_url,\n \"stream\": args.stream,\n \"durable\": args.durable,\n \"batch\": args.batch,\n \"subjects\": args.subject or list(DEFAULT_KERNEL_PRODUCT_SUBJECTS),\n \"ack\": not args.no_ack,\n \"source_cache_dir\": str(output.parent / \"primitive_bus_sources\"),\n \"source_cards_path\": str(output.parent / \"event_bus_source_cards.jsonl\"),\n }\n output.write_text(json.dumps(payload, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n emit_result({\"written\": True, \"path\": str(output), \"adapter\": payload})\n elif args.command == \"bus-poll\":\n from .bus_poller import poll_loop, resolve_status_path\n\n status_path = args.status_path or resolve_status_path(args.adapter)\n state = poll_loop(\n adapter=args.adapter,\n inbox=args.inbox,\n interval_seconds=args.interval,\n status_path=status_path,\n max_ticks=args.max_ticks,\n )\n emit_result(state.snapshot())\n elif args.command == \"run-kernel-bus-product-node\":\n results = []\n for _index in range(max(1, args.iterations)):\n imported = import_bus_events(adapter=args.adapter, inbox=args.inbox)\n product = run_product_node(\n events_path=args.inbox,\n output_root=args.output_root,\n state_path=args.state,\n target_size=args.target_size,\n target_count=args.target_count,\n min_value_score=args.min_value_score,\n min_source_diversity=args.min_source_diversity,\n classifier=args.classifier,\n dedupe_threshold=args.dedupe_threshold,\n reviewer=args.reviewer,\n delivery_shapes=tuple(args.delivery_shape),\n iterations=1,\n poll_seconds=0,\n standing_orders_path=args.standing_orders,\n curation_plan_path=args.curation_plan,\n )\n results.append({\"import\": imported, \"product\": product})\n if args.iterations > 1 and args.poll_seconds > 0:\n import time\n\n time.sleep(args.poll_seconds)\n emit_result(\n {\n \"passed\": all(item[\"product\"][\"passed\"] for item in results),\n \"adapter\": args.adapter,\n \"inbox\": args.inbox,\n \"output_root\": args.output_root,\n \"iterations\": len(results),\n \"imported_count\": sum(item[\"import\"].get(\"imported_count\", 0) for item in results),\n \"releases_created\": sum(item[\"product\"].get(\"releases_created\", 0) for item in results),\n \"results\": results,\n }\n )\n elif args.command == \"run-product-node\":\n result = run_product_node(\n events_path=args.events,\n output_root=args.output_root,\n state_path=args.state,\n target_size=args.target_size,\n target_count=args.target_count,\n min_value_score=args.min_value_score,\n min_source_diversity=args.min_source_diversity,\n classifier=args.classifier,\n dedupe_threshold=args.dedupe_threshold,\n reviewer=args.reviewer,\n iterations=args.iterations,\n poll_seconds=args.poll_seconds,\n delivery_shapes=tuple(args.delivery_shape),\n standing_orders_path=args.standing_orders,\n curation_plan_path=args.curation_plan,\n )\n emit_result(result)\n elif args.command == \"plan-curation\":\n result = plan_curation(\n events_path=args.events,\n standing_orders_path=args.standing_orders,\n output_path=args.output,\n min_value_score=args.min_value_score,\n classifier=args.classifier,\n max_opportunities=args.max_opportunities,\n )\n emit_result({\"passed\": True, **result})\n elif args.command == \"write-standing-orders\":\n from .curation_brain import StandingOrder\n\n result = write_standing_orders(\n args.output,\n [\n StandingOrder(\n order_id=args.order_id,\n priority=args.priority,\n focus_families=tuple(args.focus_family),\n product_kinds=tuple(args.product_kind),\n keywords=tuple(item.lower() for item in args.keyword),\n banned_keywords=tuple(item.lower() for item in args.banned_keyword),\n min_value_score=args.min_value_score,\n target_count=args.target_count,\n require_complementary_bundle=not args.no_complementary_bundle,\n research_allowed=args.research_allowed,\n source=\"cli\",\n notes=args.notes,\n )\n ],\n )\n emit_result({\"passed\": True, \"path\": args.output, **result})\n elif args.command == \"verify-product-planner-state\":\n result = verify_planner_state(args.state)\n emit_result(result)\n elif args.command == \"verify-product-queues\":\n result = verify_planner_queues(args.queues)\n emit_result(result)\n elif args.command == \"verify-autonomous-release\":\n result = verify_autonomous_release(args.manifest)\n emit_result(result)\n elif args.command == \"verify-commercial-release\":\n result = verify_commercial_release(args.release_dir)\n emit_result(result)\n elif args.command == \"verify-external-listing\":\n result = verify_external_listing_release(args.release_dir)\n emit_result(result)\n elif args.command == \"write-marketplace-packets\":\n result = write_marketplace_packets(release_dir=args.release_dir, output_dir=args.output_dir)\n emit_result(result)\n elif args.command == \"write-aws-data-exchange-package\":\n result = write_aws_data_exchange_package(\n release_dir=args.release_dir,\n output_dir=args.output_dir,\n product_title=args.product_title,\n price_usd=args.price_usd,\n duration_days=args.duration_days,\n support_contact=args.support_contact,\n refund_policy=args.refund_policy,\n subscription_verification=not args.no_subscription_verification,\n provider_account_ready=args.provider_account_ready,\n )\n emit_result(result)\n elif args.command == \"verify-aws-data-exchange-package\":\n result = verify_aws_data_exchange_package(args.package_dir)\n emit_result(result)\n elif args.command == \"build-preview\":\n path = build_buyer_preview(\n Path(args.release_dir),\n preview_records=args.preview_records,\n redact_ground_truth=not args.include_ground_truth,\n )\n emit_result({\"passed\": True, \"preview_dir\": str(path)})\n elif args.command == \"approve-external-listing\":\n result = approve_external_listing(\n release_dir=args.release_dir,\n reviewer=args.reviewer,\n notes=args.notes,\n support_contact=args.support_contact,\n refund_policy=args.refund_policy,\n tax_vat_status=args.tax_vat_status,\n package_output_dir=args.package_output_dir,\n )\n emit_result(result)\n elif args.command == \"refresh-release-package\":\n result = refresh_release_package(\n release_dir=args.release_dir,\n package_output_dir=args.package_output_dir,\n )\n emit_result(result)\n elif args.command == \"repair-release-artifacts\":\n result = repair_release_artifacts(\n release_dir=args.release_dir,\n package_output_dir=args.package_output_dir,\n )\n emit_result(result)\n elif args.command == \"verify-sterilized-bundle\":\n result = verify_sterilized_bundle(args.bundle_dir)\n emit_result(result)\n elif args.command == \"verify-sterilized-jsonl\":\n result = verify_sterilized_jsonl(args.path)\n emit_result(result)\n elif args.command == \"product-planner-health\":\n result = planner_health(output_root=args.output_root, state_path=args.state)\n emit_result(result)\n else:\n parser.error(f\"unhandled command: {args.command}\")\n except (ValueError, FileNotFoundError, json.JSONDecodeError, KeyError, OSError, RuntimeError) as error:\n parser.error(str(error))","instruction":"Explain the role of `def main() -> None` in Primitive Foundry.","output":"`main` is a function in `primitive_foundry.cli`. It belongs to the release, marketplace, commercial, bus, planner, curation, dataset, router, benchmark, source_card area of Primitive Foundry.","source_id":"primitive_foundry.cli.main","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.write_commercial_artifacts::explain","input":"Module: primitive_foundry.commercial\nDomains: sterilization, privacy, release, marketplace, commercial, license, dataset, benchmark, exporter, compliance, source_card\nSource path: primitive_foundry/commercial.py\n\ndef write_commercial_artifacts(\n *,\n release_dir: str | Path,\n release_id: str,\n family: str,\n target_size: str,\n target_count: int | None = None,\n record_count: int,\n source_diversity: int,\n candidate: dict[str, Any],\n build_context: BuildContext = DEFAULT_BUILD_CONTEXT,\n) -> dict[str, Any]:\n directory = Path(release_dir)\n directory.mkdir(parents=True, exist_ok=True)\n profile = COMMERCIAL_SIZE_PROFILES[target_size]\n economics = candidate.get(\"product_economics\", {})\n license_tier = str(candidate.get(\"license_tier\") or economics.get(\"license_tier\") or \"internal_eval_only\")\n review_level = str(candidate.get(\"review_level\") or economics.get(\"review_level\") or \"founder_attested\")\n price = estimate_price(\n profile[\"base_price_usd\"],\n economics,\n record_count,\n profile[\"records\"],\n license_tier=license_tier,\n review_level=review_level,\n )\n sku = sku_for_release(family, target_size, release_id)\n version = version_for_release(release_id)\n pricing = pricing_evidence(\n profile=profile,\n economics=economics,\n record_count=record_count,\n profile_records=profile[\"records\"],\n price=price,\n license_tier=license_tier,\n review_level=review_level,\n )\n sample_policy = buyer_sample_policy(release_id, family, record_count)\n version_policy = release_version_policy(release_id, sku, version, target_size)\n marketplace = marketplace_metadata(\n sku=sku,\n family=family,\n target_size=target_size,\n title=f\"{family_title(family)} ({profile['commercial_tier'].title()})\",\n description=commercial_description(family, target_size, record_count),\n price=price,\n )\n legal_review = legal_review_packet(release_id, sku)\n listing = {\n \"manifest_type\": \"aml_marketplace_listing\",\n \"sku\": sku,\n \"release_id\": release_id,\n \"version\": version,\n \"title\": f\"{family_title(family)} ({profile['commercial_tier'].title()})\",\n \"family\": family,\n \"target_size\": target_size,\n \"target_count\": target_count or profile[\"records\"],\n \"profile_record_count\": profile[\"records\"],\n \"commercial_tier\": profile[\"commercial_tier\"],\n \"record_count\": record_count,\n \"source_diversity\": source_diversity,\n \"recommended_use\": profile[\"recommended_use\"],\n \"description\": commercial_description(family, target_size, record_count),\n \"included_artifacts\": [\n \"Foundry-compatible bundle\",\n \"buyer manifest\",\n \"provenance manifest\",\n \"quality report\",\n \"sample split files\",\n \"promotion manifest\",\n \"review manifest\",\n \"manifest lock\",\n \"commercial readiness manifest\",\n ],\n \"excluded_artifacts\": [\"raw private source files\", \"private source-card drafts\", \"raw internal traces\"],\n \"license\": \"private-commercial-evaluation\",\n \"license_tier\": license_tier,\n \"review_level\": review_level,\n \"usage_rights\": [\n \"internal evaluation\",\n \"benchmarking\",\n \"model/routing assessment\",\n \"derived metrics and reports\",\n ],\n \"restrictions\": [\n \"no redistribution\",\n \"no external upload without explicit approval\",\n \"no raw source reconstruction attempts\",\n \"no resale as a competing dataset\",\n ],\n \"price_usd\": price,\n \"pricing_method\": pricing[\"pricing_method\"],\n \"currency\": \"USD\",\n \"market_regions\": [\"US\", \"EU\"],\n \"delivery_format\": \"tar.gz\",\n \"compliance\": {\n \"market_regions\": list(MARKET_REGIONS),\n \"frameworks\": COMPLIANCE_FRAMEWORKS,\n \"raw_sources_included\": False,\n \"personal_data_included\": False,\n \"sensitive_personal_data_included\": False,\n \"personal_information_sold_or_shared\": False,\n \"sensitive_personal_information_included\": False,\n \"pseudonymised_personal_data_included\": False,\n \"anonymous_or_derived_only\": True,\n \"source_hashes_included\": True,\n \"provenance_hashes_included\": True,\n \"patent_sensitive\": True,\n \"claims_basis\": \"verified manifest lock, package hash, provenance hashes, promotion manifest, and review manifest\",\n \"us_ftc_posture\": \"privacy, security, and quality claims are limited to verified package contents\",\n \"us_ccpa_cpra_posture\": \"not sold or shared as personal information; no sensitive personal information included\",\n \"eu_gdpr_posture\": \"non-personal derived benchmark records only; no raw source files included\",\n \"eu_data_act_posture\": \"commercial transfer includes manifest, provenance, schema, quality report, and terms\",\n },\n \"regional_compliance\": {\n \"US\": {\n \"frameworks\": [\"FTC privacy/security claims\", \"CCPA/CPRA personal information controls\"],\n \"personal_information_sold_or_shared\": False,\n \"sensitive_personal_information_included\": False,\n \"privacy_claims_must_match_package\": True,\n },\n \"EU\": {\n \"frameworks\": [\"GDPR personal data/anonymisation\", \"data minimisation\"],\n \"personal_data_included\": False,\n \"pseudonymised_personal_data_included\": False,\n \"anonymous_or_derived_only\": True,\n \"data_minimisation_applied\": True,\n },\n },\n \"quality\": {\n \"benchmark_pass_rate\": gate_actual(candidate, \"benchmark_pass_rate\"),\n \"sterilization_passed\": candidate_sterilization_passed(candidate),\n \"product_economics\": economics,\n \"promotion_passed\": any(\n gate.get(\"name\") == \"promotion_quality\" and gate.get(\"passed\")\n for gate in candidate.get(\"quality_gates\", [])\n ),\n \"review_passed\": any(\n gate.get(\"name\") == \"review_quality\" and gate.get(\"passed\")\n for gate in candidate.get(\"quality_gates\", [])\n ),\n },\n \"marketplace_metadata_hash\": sha256_json(marketplace),\n \"buyer_sample_policy_hash\": sha256_json(sample_policy),\n \"version_policy_hash\": sha256_json(version_policy),\n \"pricing_evidence_hash\": sha256_json(pricing),\n \"legal_review_hash\": sha256_json(legal_review),\n \"externally_listable\": False,\n \"created_at\": build_context.now(),\n }\n listing[\"listing_hash\"] = sha256_json({**listing, \"listing_hash\": \"\"})\n readiness = commercial_readiness(listing, candidate, build_context=build_context)\n terms = commercial_terms(listing)\n\n listing_path = directory / \"MARKETPLACE_LISTING.json\"\n readiness_path = directory / \"COMMERCIAL_READINESS.json\"\n terms_path = directory / \"TERMS.md\"\n marketplace_path = directory / \"MARKETPLACE_METADATA.json\"\n channel_plan_path = directory / \"MARKETPLACE_CHANNEL_PLAN.json\"\n sample_policy_path = directory / \"BUYER_SAMPLE_POLICY.json\"\n version_policy_path = directory / \"VERSION_POLICY.json\"\n pricing_path = directory / \"PRICING_EVIDENCE.json\"\n legal_path = directory / \"LEGAL_REVIEW_PACKET.json\"\n listing_path.write_text(json.dumps(listing, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n readiness_path.write_text(json.dumps(readiness, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n terms_path.write_text(terms, encoding=\"utf-8\")\n marketplace_path.write_text(json.dumps(marketplace, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n sample_policy_path.write_text(json.dumps(sample_policy, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n version_policy_path.write_text(json.dumps(version_policy, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n pricing_path.write_text(json.dumps(pricing, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n legal_path.write_text(json.dumps(legal_review, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n channel_plan = write_marketplace_channel_plan(\n release_dir=directory,\n listing=listing,\n marketplace_metadata=marketplace,\n build_context=build_context,\n )\n # Industry-standard sibling artifacts (Croissant, schema.org/Dataset,\n # DCAT-3). Written at the release root, not in bundle/, so the\n # MANIFEST.lock seal is not invalidated.\n from .exporters import write_croissant, write_datasheet, write_dcat, write_schema_org_dataset\n from .compliance import write_compliance_matrix\n\n write_croissant(directory, listing)\n write_schema_org_dataset(directory, listing)\n write_dcat(directory, listing)\n write_datasheet(directory, listing)\n source_cards = _load_source_cards_for_compliance(directory)\n write_compliance_matrix(release_dir=directory, listing=listing, source_cards=source_cards)\n return {\n \"listing\": str(listing_path),\n \"readiness\": str(readiness_path),\n \"terms\": str(terms_path),\n \"marketplace_metadata\": str(marketplace_path),\n \"marketplace_channel_plan\": str(channel_plan_path),\n \"buyer_sample_policy\": str(sample_policy_path),\n \"version_policy\": str(version_policy_path),\n \"pricing_evidence\": str(pricing_path),\n \"legal_review_packet\": str(legal_path),\n \"croissant\": str(directory / \"CROISSANT.jsonld\"),\n \"schema_org_dataset\": str(directory / \"SCHEMA_ORG_DATASET.jsonld\"),\n \"dcat\": str(directory / \"DCAT.jsonld\"),\n \"compliance_matrix\": str(directory / \"COMPLIANCE_MATRIX.json\"),\n \"datasheet\": str(directory / \"DATASHEET.md\"),\n \"listing_payload\": listing,\n \"readiness_payload\": readiness,\n \"channel_plan_payload\": channel_plan[\"payload\"],\n }","instruction":"Explain the role of `def write_commercial_artifacts(*, release_dir: str | Path, release_id: str, family: str, target_size: str, target_count: int | None=None, record_count: int, source_diversity: int, candidate: dict[str, Any], build_context: BuildContext=DEFAULT_BUILD_CONTEXT) -> dict[str, Any]` in Primitive Foundry.","output":"`write_commercial_artifacts` is a function in `primitive_foundry.commercial`. It belongs to the sterilization, privacy, release, marketplace, commercial, license, dataset, benchmark, exporter, compliance, source_card area of Primitive Foundry.","source_id":"primitive_foundry.commercial.write_commercial_artifacts","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.verify_commercial_release::explain","input":"Module: primitive_foundry.commercial\nDomains: release, marketplace, commercial, license, compliance\nSource path: primitive_foundry/commercial.py\n\ndef verify_commercial_release(release_dir: str | Path) -> dict[str, Any]:\n directory = Path(release_dir)\n failures = []\n listing_path = directory / \"MARKETPLACE_LISTING.json\"\n readiness_path = directory / \"COMMERCIAL_READINESS.json\"\n terms_path = directory / \"TERMS.md\"\n marketplace_path = directory / \"MARKETPLACE_METADATA.json\"\n channel_plan_path = directory / \"MARKETPLACE_CHANNEL_PLAN.json\"\n sample_policy_path = directory / \"BUYER_SAMPLE_POLICY.json\"\n version_policy_path = directory / \"VERSION_POLICY.json\"\n pricing_path = directory / \"PRICING_EVIDENCE.json\"\n legal_path = directory / \"LEGAL_REVIEW_PACKET.json\"\n for path in (\n listing_path,\n readiness_path,\n terms_path,\n marketplace_path,\n channel_plan_path,\n sample_policy_path,\n version_policy_path,\n pricing_path,\n legal_path,\n ):\n if not path.exists():\n failures.append(f\"missing:{path.name}\")\n if failures:\n return {\"passed\": False, \"release_dir\": str(directory), \"failures\": failures}\n\n listing = json.loads(listing_path.read_text(encoding=\"utf-8\"))\n readiness = json.loads(readiness_path.read_text(encoding=\"utf-8\"))\n marketplace = json.loads(marketplace_path.read_text(encoding=\"utf-8\"))\n channel_plan = json.loads(channel_plan_path.read_text(encoding=\"utf-8\"))\n sample_policy = json.loads(sample_policy_path.read_text(encoding=\"utf-8\"))\n version_policy = json.loads(version_policy_path.read_text(encoding=\"utf-8\"))\n pricing = json.loads(pricing_path.read_text(encoding=\"utf-8\"))\n legal_review = json.loads(legal_path.read_text(encoding=\"utf-8\"))\n if listing.get(\"manifest_type\") != \"aml_marketplace_listing\":\n failures.append(\"invalid_listing_type\")\n if listing.get(\"listing_hash\") != sha256_json({**listing, \"listing_hash\": \"\"}):\n failures.append(\"listing_hash_mismatch\")\n if readiness.get(\"manifest_type\") != \"aml_commercial_readiness\":\n failures.append(\"invalid_readiness_type\")\n if readiness.get(\"readiness_hash\") != sha256_json({**readiness, \"readiness_hash\": \"\"}):\n failures.append(\"readiness_hash_mismatch\")\n required_listing = [\n \"sku\",\n \"release_id\",\n \"family\",\n \"title\",\n \"description\",\n \"record_count\",\n \"target_count\",\n \"target_size\",\n \"profile_record_count\",\n \"source_diversity\",\n \"commercial_tier\",\n \"price_usd\",\n \"currency\",\n \"delivery_format\",\n \"pricing_method\",\n \"license\",\n \"license_tier\",\n \"review_level\",\n \"usage_rights\",\n \"restrictions\",\n \"included_artifacts\",\n \"excluded_artifacts\",\n \"market_regions\",\n \"compliance\",\n \"version\",\n \"marketplace_metadata_hash\",\n \"buyer_sample_policy_hash\",\n \"version_policy_hash\",\n \"pricing_evidence_hash\",\n \"legal_review_hash\",\n ]\n for key in required_listing:\n if listing.get(key) in (None, \"\", [], {}):\n failures.append(f\"listing_missing:{key}\")\n compliance = listing.get(\"compliance\", {})\n if set(listing.get(\"market_regions\", [])) != set(MARKET_REGIONS):\n failures.append(\"market_regions_not_us_eu\")\n if set(compliance.get(\"market_regions\", [])) != set(MARKET_REGIONS):\n failures.append(\"compliance_regions_not_us_eu\")\n framework_regions = {row.get(\"region\") for row in compliance.get(\"frameworks\", [])}\n if not set(MARKET_REGIONS).issubset(framework_regions):\n failures.append(\"missing_regional_frameworks\")\n if compliance.get(\"raw_sources_included\") is not False:\n failures.append(\"raw_sources_included\")\n if compliance.get(\"personal_data_included\") is not False:\n failures.append(\"personal_data_included\")\n if compliance.get(\"sensitive_personal_data_included\") is not False:\n failures.append(\"sensitive_personal_data_included\")\n if compliance.get(\"personal_information_sold_or_shared\") is not False:\n failures.append(\"personal_information_sold_or_shared\")\n linked_hashes = {\n \"marketplace_metadata_hash\": marketplace,\n \"buyer_sample_policy_hash\": sample_policy,\n \"version_policy_hash\": version_policy,\n \"pricing_evidence_hash\": pricing,\n \"legal_review_hash\": legal_review,\n }\n for field, payload in linked_hashes.items():\n if listing.get(field) != sha256_json(payload):\n failures.append(f\"{field}_mismatch\")\n failures.extend(verify_marketplace_metadata_payload(marketplace, listing))\n failures.extend(verify_marketplace_channel_plan_payload(channel_plan, listing))\n failures.extend(verify_sample_policy_payload(sample_policy, listing))\n failures.extend(verify_version_policy_payload(version_policy, listing))\n failures.extend(verify_pricing_payload(pricing, listing))\n failures.extend(verify_legal_review_payload(legal_review, listing))\n failed_gates = [gate[\"name\"] for gate in readiness.get(\"gates\", []) if not gate.get(\"passed\")]\n if failed_gates:\n failures.append(\"failed_readiness_gates:\" + \",\".join(failed_gates))\n terms = terms_path.read_text(encoding=\"utf-8\")\n for phrase in (\n \"No redistribution\",\n \"No raw source files\",\n \"Private commercial evaluation\",\n \"No personal data\",\n \"No sensitive personal data\",\n \"GDPR\",\n \"CCPA/CPRA\",\n \"FTC\",\n \"EU Data Act\",\n ):\n if phrase not in terms:\n failures.append(f\"terms_missing:{phrase}\")\n return {\n \"passed\": not failures,\n \"release_dir\": str(directory),\n \"sku\": listing.get(\"sku\"),\n \"price_usd\": listing.get(\"price_usd\"),\n \"commercial_tier\": listing.get(\"commercial_tier\"),\n \"externally_listable\": bool(listing.get(\"externally_listable\")) and legal_review.get(\"legal_review\", {}).get(\"approved\") is True,\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_commercial_release(release_dir: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_commercial_release` is a function in `primitive_foundry.commercial`. It belongs to the release, marketplace, commercial, license, compliance area of Primitive Foundry.","source_id":"primitive_foundry.commercial.verify_commercial_release","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.commercial_readiness::explain","input":"Module: primitive_foundry.commercial\nDomains: sterilization, privacy, release, marketplace, commercial, compliance\nSource path: primitive_foundry/commercial.py\n\ndef commercial_readiness(\n listing: dict[str, Any],\n candidate: dict[str, Any],\n build_context: BuildContext = DEFAULT_BUILD_CONTEXT,\n) -> dict[str, Any]:\n record_count = int(listing[\"record_count\"])\n compliance = listing[\"compliance\"]\n gates = [\n {\n \"name\": \"record_count_matches_target\",\n \"passed\": record_count >= int(listing[\"target_count\"]),\n \"actual\": record_count,\n \"threshold\": int(listing[\"target_count\"]),\n },\n {\n \"name\": \"source_diversity\",\n \"passed\": int(listing[\"source_diversity\"]) >= min(3, record_count),\n \"actual\": int(listing[\"source_diversity\"]),\n \"threshold\": min(3, record_count),\n },\n {\n \"name\": \"price_present\",\n \"passed\": listing[\"price_usd\"] > 0,\n \"actual\": listing[\"price_usd\"],\n \"threshold\": \">0\",\n },\n {\n \"name\": \"marketplace_metadata_present\",\n \"passed\": bool(listing.get(\"marketplace_metadata_hash\")),\n \"actual\": bool(listing.get(\"marketplace_metadata_hash\")),\n \"threshold\": True,\n },\n {\n \"name\": \"buyer_sample_policy_present\",\n \"passed\": bool(listing.get(\"buyer_sample_policy_hash\")),\n \"actual\": bool(listing.get(\"buyer_sample_policy_hash\")),\n \"threshold\": True,\n },\n {\n \"name\": \"version_policy_present\",\n \"passed\": bool(listing.get(\"version_policy_hash\")),\n \"actual\": bool(listing.get(\"version_policy_hash\")),\n \"threshold\": True,\n },\n {\n \"name\": \"pricing_evidence_present\",\n \"passed\": bool(listing.get(\"pricing_evidence_hash\")),\n \"actual\": bool(listing.get(\"pricing_evidence_hash\")),\n \"threshold\": True,\n },\n {\n \"name\": \"legal_review_packet_present\",\n \"passed\": bool(listing.get(\"legal_review_hash\")),\n \"actual\": bool(listing.get(\"legal_review_hash\")),\n \"threshold\": True,\n },\n {\n \"name\": \"promotion_passed\",\n \"passed\": bool(listing[\"quality\"][\"promotion_passed\"]),\n \"actual\": bool(listing[\"quality\"][\"promotion_passed\"]),\n \"threshold\": True,\n },\n {\n \"name\": \"review_passed\",\n \"passed\": bool(listing[\"quality\"][\"review_passed\"]),\n \"actual\": bool(listing[\"quality\"][\"review_passed\"]),\n \"threshold\": True,\n },\n {\n \"name\": \"no_raw_sources\",\n \"passed\": compliance[\"raw_sources_included\"] is False,\n \"actual\": compliance[\"raw_sources_included\"],\n \"threshold\": False,\n },\n {\n \"name\": \"sterilization_passed\",\n \"passed\": bool(listing[\"quality\"][\"sterilization_passed\"]),\n \"actual\": bool(listing[\"quality\"][\"sterilization_passed\"]),\n \"threshold\": True,\n },\n {\n \"name\": \"us_eu_regions_declared\",\n \"passed\": set(listing[\"market_regions\"]) == set(MARKET_REGIONS)\n and set(compliance[\"market_regions\"]) == set(MARKET_REGIONS),\n \"actual\": listing[\"market_regions\"],\n \"threshold\": list(MARKET_REGIONS),\n },\n {\n \"name\": \"frameworks_declared\",\n \"passed\": set(MARKET_REGIONS).issubset({row.get(\"region\") for row in compliance[\"frameworks\"]}),\n \"actual\": sorted({row.get(\"region\") for row in compliance[\"frameworks\"]}),\n \"threshold\": list(MARKET_REGIONS),\n },\n {\n \"name\": \"no_personal_data\",\n \"passed\": compliance[\"personal_data_included\"] is False,\n \"actual\": compliance[\"personal_data_included\"],\n \"threshold\": False,\n },\n {\n \"name\": \"no_sensitive_personal_data\",\n \"passed\": compliance[\"sensitive_personal_data_included\"] is False,\n \"actual\": compliance[\"sensitive_personal_data_included\"],\n \"threshold\": False,\n },\n {\n \"name\": \"us_no_personal_information_sale\",\n \"passed\": compliance[\"personal_information_sold_or_shared\"] is False\n and listing[\"regional_compliance\"][\"US\"][\"personal_information_sold_or_shared\"] is False,\n \"actual\": compliance[\"personal_information_sold_or_shared\"],\n \"threshold\": False,\n },\n {\n \"name\": \"us_no_sensitive_personal_information\",\n \"passed\": compliance[\"sensitive_personal_information_included\"] is False\n and listing[\"regional_compliance\"][\"US\"][\"sensitive_personal_information_included\"] is False,\n \"actual\": compliance[\"sensitive_personal_information_included\"],\n \"threshold\": False,\n },\n {\n \"name\": \"eu_no_personal_data\",\n \"passed\": compliance[\"personal_data_included\"] is False\n and listing[\"regional_compliance\"][\"EU\"][\"personal_data_included\"] is False,\n \"actual\": compliance[\"personal_data_included\"],\n \"threshold\": False,\n },\n {\n \"name\": \"eu_no_pseudonymised_personal_data\",\n \"passed\": compliance[\"pseudonymised_personal_data_included\"] is False\n and listing[\"regional_compliance\"][\"EU\"][\"pseudonymised_personal_data_included\"] is False,\n \"actual\": compliance[\"pseudonymised_personal_data_included\"],\n \"threshold\": False,\n },\n {\n \"name\": \"eu_anonymous_or_derived_only\",\n \"passed\": compliance[\"anonymous_or_derived_only\"] is True\n and listing[\"regional_compliance\"][\"EU\"][\"anonymous_or_derived_only\"] is True,\n \"actual\": compliance[\"anonymous_or_derived_only\"],\n \"threshold\": True,\n },\n {\n \"name\": \"eu_data_minimisation\",\n \"passed\": listing[\"regional_compliance\"][\"EU\"][\"data_minimisation_applied\"] is True,\n \"actual\": listing[\"regional_compliance\"][\"EU\"][\"data_minimisation_applied\"],\n \"threshold\": True,\n },\n {\n \"name\": \"truthful_privacy_claims_basis\",\n \"passed\": bool(compliance[\"claims_basis\"]) and listing[\"regional_compliance\"][\"US\"][\"privacy_claims_must_match_package\"],\n \"actual\": compliance[\"claims_basis\"],\n \"threshold\": \"verified package evidence\",\n },\n {\n \"name\": \"candidate_passed\",\n \"passed\": bool(candidate.get(\"passed\")),\n \"actual\": bool(candidate.get(\"passed\")),\n \"threshold\": True,\n },\n ]\n readiness = {\n \"manifest_type\": \"aml_commercial_readiness\",\n \"sku\": listing[\"sku\"],\n \"release_id\": listing[\"release_id\"],\n \"created_at\": build_context.now(),\n \"commercially_ready\": all(gate[\"passed\"] for gate in gates),\n \"gates\": gates,\n }\n readiness[\"readiness_hash\"] = sha256_json({**readiness, \"readiness_hash\": \"\"})\n return readiness","instruction":"Explain the role of `def commercial_readiness(listing: dict[str, Any], candidate: dict[str, Any], build_context: BuildContext=DEFAULT_BUILD_CONTEXT) -> dict[str, Any]` in Primitive Foundry.","output":"`commercial_readiness` is a function in `primitive_foundry.commercial`. It belongs to the sterilization, privacy, release, marketplace, commercial, compliance area of Primitive Foundry.","source_id":"primitive_foundry.commercial.commercial_readiness","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.commercial_terms::explain","input":"Module: primitive_foundry.commercial\nDomains: privacy, marketplace, commercial, license, dataset, benchmark\nSource path: primitive_foundry/commercial.py\n\ndef commercial_terms(listing: dict[str, Any]) -> str:\n return (\n f\"# Terms: {listing['sku']}\\n\\n\"\n \"Private commercial evaluation license.\\n\\n\"\n \"## Allowed Uses\\n\"\n \"- Internal evaluation\\n\"\n \"- Benchmarking\\n\"\n \"- Model and routing assessment\\n\"\n \"- Derived metrics and reports\\n\\n\"\n \"## Restrictions\\n\"\n \"- No redistribution\\n\"\n \"- No external upload without explicit approval\\n\"\n \"- No sale or sharing of personal information\\n\"\n \"- No raw source files are included or licensed\\n\"\n \"- No raw source reconstruction attempts\\n\"\n \"- No resale as a competing dataset\\n\\n\"\n \"## US/EU Privacy Position\\n\"\n \"This package is offered as derived/anonymized benchmark material for US and EU markets. \"\n \"No personal data is intentionally included. No sensitive personal data is intentionally included. \"\n \"It is not sold as personal information, sensitive personal information, or pseudonymized personal data.\\n\\n\"\n \"The listing uses a market-readiness posture for GDPR, CCPA/CPRA, FTC privacy/security claim alignment, \"\n \"and EU Data Act transparency. It is not a legal certification.\\n\\n\"\n \"## Privacy\\n\"\n \"No raw source files are included. Provenance and source hashes are included for auditability.\\n\"\n \"\\n## External Listing Gate\\n\"\n \"External marketplace listing requires an approved legal review packet and an externally_listable=true listing flag.\\n\"\n )","instruction":"Explain the role of `def commercial_terms(listing: dict[str, Any]) -> str` in Primitive Foundry.","output":"`commercial_terms` is a function in `primitive_foundry.commercial`. It belongs to the privacy, marketplace, commercial, license, dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.commercial.commercial_terms","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.gate_actual::explain","input":"Module: primitive_foundry.commercial\nDomains: commercial\nSource path: primitive_foundry/commercial.py\n\ndef gate_actual(candidate: dict[str, Any], name: str) -> Any:\n for gate in candidate.get(\"quality_gates\", []):\n if gate.get(\"name\") == name:\n return gate.get(\"actual\")\n return None","instruction":"Explain the role of `def gate_actual(candidate: dict[str, Any], name: str) -> Any` in Primitive Foundry.","output":"`gate_actual` is a function in `primitive_foundry.commercial`. It belongs to the commercial area of Primitive Foundry.","source_id":"primitive_foundry.commercial.gate_actual","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.candidate_sterilization_passed::explain","input":"Module: primitive_foundry.commercial\nDomains: sterilization, release, commercial\nSource path: primitive_foundry/commercial.py\n\ndef candidate_sterilization_passed(candidate: dict[str, Any]) -> bool:\n quality = candidate.get(\"quality\", {})\n if quality.get(\"sterilization_passed\") is True:\n return True\n for gate in candidate.get(\"quality_gates\", []):\n if gate.get(\"name\") == \"sterilization_quality\" and gate.get(\"passed\"):\n return True\n # Older release manifests predate the explicit sterilization gate but used\n # verified Foundry bundles as the packaging boundary.\n return any(gate.get(\"name\") == \"bundle_quality\" and gate.get(\"passed\") for gate in candidate.get(\"quality_gates\", []))","instruction":"Explain the role of `def candidate_sterilization_passed(candidate: dict[str, Any]) -> bool` in Primitive Foundry.","output":"`candidate_sterilization_passed` is a function in `primitive_foundry.commercial`. It belongs to the sterilization, release, commercial area of Primitive Foundry.","source_id":"primitive_foundry.commercial.candidate_sterilization_passed","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.estimate_price::explain","input":"Module: primitive_foundry.commercial\nDomains: commercial, license\nSource path: primitive_foundry/commercial.py\n\ndef estimate_price(\n base_price: int,\n economics: dict[str, Any],\n record_count: int,\n profile_records: int,\n *,\n license_tier: str = \"internal_eval_only\",\n review_level: str = \"automated_only\",\n) -> int:\n value = float(economics.get(\"estimated_buyer_value\", 0.75) or 0.75)\n scale = max(1.0, record_count / max(1, profile_records))\n raw = base_price * scale * (0.75 + value)\n raw *= LICENSE_TIER_MULTIPLIER[license_tier]\n raw *= REVIEW_LEVEL_MULTIPLIER[review_level]\n return int(round(raw, -1))","instruction":"Explain the role of `def estimate_price(base_price: int, economics: dict[str, Any], record_count: int, profile_records: int, *, license_tier: str='internal_eval_only', review_level: str='automated_only') -> int` in Primitive Foundry.","output":"`estimate_price` is a function in `primitive_foundry.commercial`. It belongs to the commercial, license area of Primitive Foundry.","source_id":"primitive_foundry.commercial.estimate_price","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.pricing_evidence::explain","input":"Module: primitive_foundry.commercial\nDomains: commercial, license\nSource path: primitive_foundry/commercial.py\n\ndef pricing_evidence(\n *,\n profile: dict[str, Any],\n economics: dict[str, Any],\n record_count: int,\n profile_records: int,\n price: int,\n license_tier: str,\n review_level: str,\n) -> dict[str, Any]:\n value = float(economics.get(\"estimated_buyer_value\", 0.75) or 0.75)\n scale = max(1.0, record_count / max(1, profile_records))\n payload = {\n \"manifest_type\": \"aml_pricing_evidence\",\n \"pricing_method\": (\n \"base_profile_price * max(1, record_count/profile_records) * \"\n \"(0.75 + estimated_buyer_value) * license_tier_multiplier * review_level_multiplier\"\n ),\n \"base_price_usd\": profile[\"base_price_usd\"],\n \"commercial_tier\": profile[\"commercial_tier\"],\n \"record_count\": record_count,\n \"profile_record_count\": profile_records,\n \"scale_factor\": round(scale, 4),\n \"estimated_buyer_value\": round(value, 4),\n \"license_tier\": license_tier,\n \"license_tier_multiplier\": LICENSE_TIER_MULTIPLIER[license_tier],\n \"review_level\": review_level,\n \"review_level_multiplier\": REVIEW_LEVEL_MULTIPLIER[review_level],\n \"computed_price_usd\": price,\n \"pricing_status\": \"heuristic_internal_validation\",\n \"market_tested\": False,\n \"requires_market_validation_before_large_public_launch\": True,\n }\n payload[\"pricing_hash\"] = sha256_json({**payload, \"pricing_hash\": \"\"})\n return payload","instruction":"Explain the role of `def pricing_evidence(*, profile: dict[str, Any], economics: dict[str, Any], record_count: int, profile_records: int, price: int, license_tier: str, review_level: str) -> dict[str, Any]` in Primitive Foundry.","output":"`pricing_evidence` is a function in `primitive_foundry.commercial`. It belongs to the commercial, license area of Primitive Foundry.","source_id":"primitive_foundry.commercial.pricing_evidence","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.marketplace_metadata::explain","input":"Module: primitive_foundry.commercial\nDomains: marketplace, commercial, license, dataset, benchmark\nSource path: primitive_foundry/commercial.py\n\ndef marketplace_metadata(\n *,\n sku: str,\n family: str,\n target_size: str,\n title: str,\n description: str,\n price: int,\n) -> dict[str, Any]:\n payload = {\n \"manifest_type\": \"aml_marketplace_metadata\",\n \"sku\": sku,\n \"title\": title,\n \"subtitle\": \"Private, provenance-backed Primitive Foundry benchmark product\",\n \"description\": description,\n \"category\": marketplace_category(family),\n \"tags\": sorted({family, target_size, \"benchmark\", \"dataset\", \"eval\", \"provenance\", \"sterilized\"}),\n \"delivery_format\": \"tar.gz\",\n \"license\": \"private-commercial-evaluation\",\n \"support_contact_required\": True,\n \"support_contact\": \"TBD-before-external-listing\",\n \"refund_policy_required\": True,\n \"refund_policy\": \"TBD-before-external-listing\",\n \"tax_vat_required\": True,\n \"tax_vat_status\": \"seller_account_required_before-external-listing\",\n \"currency\": \"USD\",\n \"price_usd\": price,\n \"primary_marketplace\": \"aws_data_exchange\",\n \"secondary_marketplaces\": [\"snowflake_marketplace\", \"databricks_marketplace\"],\n \"community_funnel\": \"huggingface_hub\",\n \"public_sample_available\": False,\n \"private_buyer_preview_available\": True,\n }\n payload[\"metadata_hash\"] = sha256_json({**payload, \"metadata_hash\": \"\"})\n return payload","instruction":"Explain the role of `def marketplace_metadata(*, sku: str, family: str, target_size: str, title: str, description: str, price: int) -> dict[str, Any]` in Primitive Foundry.","output":"`marketplace_metadata` is a function in `primitive_foundry.commercial`. It belongs to the marketplace, commercial, license, dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.commercial.marketplace_metadata","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.buyer_sample_policy::explain","input":"Module: primitive_foundry.commercial\nDomains: sterilization, release, commercial, dataset, source_card\nSource path: primitive_foundry/commercial.py\n\ndef buyer_sample_policy(release_id: str, family: str, record_count: int) -> dict[str, Any]:\n payload = {\n \"manifest_type\": \"aml_buyer_sample_policy\",\n \"release_id\": release_id,\n \"family\": family,\n \"public_sample_policy\": \"no_public_record_sample\",\n \"private_preview_policy\": \"sterilized_sample_only_after_buyer_terms_acceptance\",\n \"max_private_preview_records\": min(25, max(1, record_count)),\n \"raw_sources_in_preview\": False,\n \"source_cards_in_preview\": False,\n \"dataset_jsonl_in_preview\": False,\n \"allowed_preview_artifacts\": [\"README.md\", \"DATASET_CARD.md\", \"SCHEMA.json\", \"QUALITY_REPORT.md\", \"sample/sample_500.jsonl\"],\n \"requires_sterilization_verification\": True,\n \"requires_terms_acceptance\": True,\n }\n payload[\"sample_policy_hash\"] = sha256_json({**payload, \"sample_policy_hash\": \"\"})\n return payload","instruction":"Explain the role of `def buyer_sample_policy(release_id: str, family: str, record_count: int) -> dict[str, Any]` in Primitive Foundry.","output":"`buyer_sample_policy` is a function in `primitive_foundry.commercial`. It belongs to the sterilization, release, commercial, dataset, source_card area of Primitive Foundry.","source_id":"primitive_foundry.commercial.buyer_sample_policy","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.legal_review_packet::explain","input":"Module: primitive_foundry.commercial\nDomains: release, marketplace, commercial, license\nSource path: primitive_foundry/commercial.py\n\ndef legal_review_packet(release_id: str, sku: str) -> dict[str, Any]:\n payload = {\n \"manifest_type\": \"aml_legal_review_packet\",\n \"release_id\": release_id,\n \"sku\": sku,\n \"legal_review\": {\n \"approved\": False,\n \"reviewer\": None,\n \"reviewed_at\": None,\n \"notes\": \"External sale is blocked until qualified legal review approves this packet.\",\n },\n \"required_review_items\": [\n \"terms_and_license\",\n \"gdpr_posture\",\n \"ccpa_cpra_posture\",\n \"ftc_claims_alignment\",\n \"eu_data_act_posture\",\n \"patent_sensitive_language\",\n \"marketplace_seller_obligations\",\n \"marketplace_channel_obligations\",\n \"tax_vat_obligations\",\n \"support_and_refund_policy\",\n ],\n \"external_sale_blocked_until_approved\": True,\n }\n payload[\"legal_packet_hash\"] = sha256_json({**payload, \"legal_packet_hash\": \"\"})\n return payload","instruction":"Explain the role of `def legal_review_packet(release_id: str, sku: str) -> dict[str, Any]` in Primitive Foundry.","output":"`legal_review_packet` is a function in `primitive_foundry.commercial`. It belongs to the release, marketplace, commercial, license area of Primitive Foundry.","source_id":"primitive_foundry.commercial.legal_review_packet","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.commercial_description::explain","input":"Module: primitive_foundry.commercial\nDomains: commercial\nSource path: primitive_foundry/commercial.py\n\ndef commercial_description(family: str, target_size: str, record_count: int) -> str:\n title = family_title(family)\n return (\n f\"{title} containing {record_count} private, source-backed records. \"\n f\"Built as a {target_size} sale profile with provenance hashes, quality gates, \"\n \"promotion/review manifests, and no raw private source files.\"\n )","instruction":"Explain the role of `def commercial_description(family: str, target_size: str, record_count: int) -> str` in Primitive Foundry.","output":"`commercial_description` is a function in `primitive_foundry.commercial`. It belongs to the commercial area of Primitive Foundry.","source_id":"primitive_foundry.commercial.commercial_description","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.sku_for_release::explain","input":"Module: primitive_foundry.commercial\nDomains: release, commercial\nSource path: primitive_foundry/commercial.py\n\ndef sku_for_release(family: str, target_size: str, release_id: str) -> str:\n compact_family = family.upper().replace(\"_\", \"-\")\n compact_size = target_size.upper()\n suffix = release_id.split(\"_\")[-1]\n return f\"PF-{compact_family}-{compact_size}-{suffix}\"","instruction":"Explain the role of `def sku_for_release(family: str, target_size: str, release_id: str) -> str` in Primitive Foundry.","output":"`sku_for_release` is a function in `primitive_foundry.commercial`. It belongs to the release, commercial area of Primitive Foundry.","source_id":"primitive_foundry.commercial.sku_for_release","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.version_for_release::explain","input":"Module: primitive_foundry.commercial\nDomains: release, commercial\nSource path: primitive_foundry/commercial.py\n\ndef version_for_release(release_id: str) -> str:\n suffix = release_id.split(\"_\")[-1].lstrip(\"0\") or \"0\"\n return f\"1.0.{suffix}\"","instruction":"Explain the role of `def version_for_release(release_id: str) -> str` in Primitive Foundry.","output":"`version_for_release` is a function in `primitive_foundry.commercial`. It belongs to the release, commercial area of Primitive Foundry.","source_id":"primitive_foundry.commercial.version_for_release","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.marketplace_category::explain","input":"Module: primitive_foundry.commercial\nDomains: marketplace, commercial\nSource path: primitive_foundry/commercial.py\n\ndef marketplace_category(family: str) -> str:\n return family_marketplace_category(family)","instruction":"Explain the role of `def marketplace_category(family: str) -> str` in Primitive Foundry.","output":"`marketplace_category` is a function in `primitive_foundry.commercial`. It belongs to the marketplace, commercial area of Primitive Foundry.","source_id":"primitive_foundry.commercial.marketplace_category","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.verify_marketplace_metadata_payload::explain","input":"Module: primitive_foundry.commercial\nDomains: marketplace, commercial, license\nSource path: primitive_foundry/commercial.py\n\ndef verify_marketplace_metadata_payload(payload: dict[str, Any], listing: dict[str, Any]) -> list[str]:\n failures = []\n if payload.get(\"manifest_type\") != \"aml_marketplace_metadata\":\n failures.append(\"invalid_marketplace_metadata_type\")\n if payload.get(\"metadata_hash\") != sha256_json({**payload, \"metadata_hash\": \"\"}):\n failures.append(\"marketplace_metadata_hash_mismatch\")\n for key in (\n \"sku\",\n \"title\",\n \"description\",\n \"category\",\n \"delivery_format\",\n \"license\",\n \"price_usd\",\n \"primary_marketplace\",\n \"secondary_marketplaces\",\n \"community_funnel\",\n ):\n if payload.get(key) in (None, \"\", [], {}):\n failures.append(f\"marketplace_missing:{key}\")\n if payload.get(\"primary_marketplace\") != \"aws_data_exchange\":\n failures.append(\"marketplace_primary_not_aws_data_exchange\")\n if payload.get(\"sku\") != listing.get(\"sku\"):\n failures.append(\"marketplace_sku_mismatch\")\n if payload.get(\"title\") != listing.get(\"title\"):\n failures.append(\"marketplace_title_mismatch\")\n if payload.get(\"description\") != listing.get(\"description\"):\n failures.append(\"marketplace_description_mismatch\")\n if payload.get(\"delivery_format\") != listing.get(\"delivery_format\"):\n failures.append(\"marketplace_delivery_format_mismatch\")\n if payload.get(\"license\") != listing.get(\"license\"):\n failures.append(\"marketplace_license_mismatch\")\n if payload.get(\"currency\") != listing.get(\"currency\"):\n failures.append(\"marketplace_currency_mismatch\")\n if payload.get(\"price_usd\") != listing.get(\"price_usd\"):\n failures.append(\"marketplace_price_mismatch\")\n return failures","instruction":"Explain the role of `def verify_marketplace_metadata_payload(payload: dict[str, Any], listing: dict[str, Any]) -> list[str]` in Primitive Foundry.","output":"`verify_marketplace_metadata_payload` is a function in `primitive_foundry.commercial`. It belongs to the marketplace, commercial, license area of Primitive Foundry.","source_id":"primitive_foundry.commercial.verify_marketplace_metadata_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.verify_sample_policy_payload::explain","input":"Module: primitive_foundry.commercial\nDomains: sterilization, release, commercial, dataset, source_card\nSource path: primitive_foundry/commercial.py\n\ndef verify_sample_policy_payload(payload: dict[str, Any], listing: dict[str, Any]) -> list[str]:\n failures = []\n if payload.get(\"manifest_type\") != \"aml_buyer_sample_policy\":\n failures.append(\"invalid_sample_policy_type\")\n if payload.get(\"sample_policy_hash\") != sha256_json({**payload, \"sample_policy_hash\": \"\"}):\n failures.append(\"sample_policy_hash_mismatch\")\n if payload.get(\"release_id\") != listing.get(\"release_id\"):\n failures.append(\"sample_policy_release_id_mismatch\")\n if payload.get(\"family\") != listing.get(\"family\"):\n failures.append(\"sample_policy_family_mismatch\")\n if payload.get(\"max_private_preview_records\", 0) > min(25, max(1, int(listing.get(\"record_count\") or 0))):\n failures.append(\"sample_policy_preview_count_exceeds_listing\")\n if payload.get(\"raw_sources_in_preview\") is not False:\n failures.append(\"sample_policy_raw_sources_allowed\")\n if payload.get(\"source_cards_in_preview\") is not False:\n failures.append(\"sample_policy_source_cards_allowed\")\n if payload.get(\"dataset_jsonl_in_preview\") is not False:\n failures.append(\"sample_policy_dataset_jsonl_allowed\")\n if payload.get(\"requires_sterilization_verification\") is not True:\n failures.append(\"sample_policy_missing_sterilization\")\n return failures","instruction":"Explain the role of `def verify_sample_policy_payload(payload: dict[str, Any], listing: dict[str, Any]) -> list[str]` in Primitive Foundry.","output":"`verify_sample_policy_payload` is a function in `primitive_foundry.commercial`. It belongs to the sterilization, release, commercial, dataset, source_card area of Primitive Foundry.","source_id":"primitive_foundry.commercial.verify_sample_policy_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.verify_legal_review_payload::explain","input":"Module: primitive_foundry.commercial\nDomains: release, marketplace, commercial, license\nSource path: primitive_foundry/commercial.py\n\ndef verify_legal_review_payload(payload: dict[str, Any], listing: dict[str, Any]) -> list[str]:\n failures = []\n if payload.get(\"manifest_type\") != \"aml_legal_review_packet\":\n failures.append(\"invalid_legal_packet_type\")\n if payload.get(\"legal_packet_hash\") != sha256_json({**payload, \"legal_packet_hash\": \"\"}):\n failures.append(\"legal_packet_hash_mismatch\")\n if payload.get(\"release_id\") != listing.get(\"release_id\"):\n failures.append(\"legal_release_id_mismatch\")\n if payload.get(\"sku\") != listing.get(\"sku\"):\n failures.append(\"legal_sku_mismatch\")\n required = set(payload.get(\"required_review_items\", []))\n expected = {\n \"terms_and_license\",\n \"gdpr_posture\",\n \"ccpa_cpra_posture\",\n \"ftc_claims_alignment\",\n \"eu_data_act_posture\",\n \"patent_sensitive_language\",\n \"marketplace_seller_obligations\",\n \"marketplace_channel_obligations\",\n \"tax_vat_obligations\",\n \"support_and_refund_policy\",\n }\n if not expected.issubset(required):\n failures.append(\"legal_packet_missing_review_items\")\n return failures","instruction":"Explain the role of `def verify_legal_review_payload(payload: dict[str, Any], listing: dict[str, Any]) -> list[str]` in Primitive Foundry.","output":"`verify_legal_review_payload` is a function in `primitive_foundry.commercial`. It belongs to the release, marketplace, commercial, license area of Primitive Foundry.","source_id":"primitive_foundry.commercial.verify_legal_review_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.is_placeholder::explain","input":"Module: primitive_foundry.commercial\nDomains: commercial\nSource path: primitive_foundry/commercial.py\n\ndef is_placeholder(value: Any) -> bool:\n text = str(value or \"\").strip().lower()\n return not text or text.startswith(\"tbd\") or \"before-external-listing\" in text","instruction":"Explain the role of `def is_placeholder(value: Any) -> bool` in Primitive Foundry.","output":"`is_placeholder` is a function in `primitive_foundry.commercial`. It belongs to the commercial area of Primitive Foundry.","source_id":"primitive_foundry.commercial.is_placeholder","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial._load_source_cards_for_compliance::explain","input":"Module: primitive_foundry.commercial\nDomains: release, commercial, license, compliance, source_card\nSource path: primitive_foundry/commercial.py\n\ndef _load_source_cards_for_compliance(release_dir: Path) -> list[dict[str, Any]]:\n \"\"\"Load source cards from the release directory if available.\n\n The compliance matrix needs the real source-card list to compute an\n accurate `source_license_matrix`. Cards are written by the factory at\n `/source_cards.jsonl` before the bundle is sealed. We read\n them defensively \u2014 a missing or unreadable file degrades gracefully to\n an empty list rather than blocking the release. (A missing file is\n flagged via `unspecified_count` downstream.)\n \"\"\"\n\n cards_path = release_dir / \"source_cards.jsonl\"\n if not cards_path.exists():\n return []\n cards: list[dict[str, Any]] = []\n try:\n with cards_path.open(\"r\", encoding=\"utf-8\") as handle:\n for line in handle:\n stripped = line.strip()\n if not stripped:\n continue\n try:\n cards.append(json.loads(stripped))\n except json.JSONDecodeError:\n continue\n except OSError:\n return []\n return cards","instruction":"Explain the role of `def _load_source_cards_for_compliance(release_dir: Path) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`_load_source_cards_for_compliance` is a function in `primitive_foundry.commercial`. It belongs to the release, commercial, license, compliance, source_card area of Primitive Foundry.","source_id":"primitive_foundry.commercial._load_source_cards_for_compliance","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.verify_complementary_bundle::explain","input":"Module: primitive_foundry.commercial\nDomains: release, marketplace, commercial, dataset, benchmark\nSource path: primitive_foundry/commercial.py\n\ndef verify_complementary_bundle(release_dir: str | Path, listing: dict[str, Any]) -> list[str]:\n directory = Path(release_dir)\n bundle = directory / \"bundle\"\n failures: list[str] = []\n\n family = str(listing.get(\"family\") or \"\")\n if family not in EVAL_FAMILIES_REQUIRING_COMPLEMENTARY_BUNDLE:\n return failures\n\n if listing.get(\"complementary_bundle_waived\") is True:\n # Explicit waiver is allowed for marketplace pilots that intentionally\n # ship dataset-only. The waiver itself is a claim and must be\n # countersigned in LEGAL_REVIEW_PACKET.json (checked separately).\n return failures\n\n dataset_present = False\n for relative in (\"data/train.jsonl\", \"data/validation.jsonl\", \"data/test.jsonl\"):\n path = bundle / relative\n if path.exists() and path.stat().st_size > 0:\n dataset_present = True\n break\n if not dataset_present:\n failures.append(\"complementary_bundle:missing_dataset_records\")\n\n rubric_path = bundle / \"RUBRIC.json\"\n if not rubric_path.exists():\n # Fall back: rubric_id at listing level is acceptable while the bundle\n # rubric file isn't on by default in older releases.\n if not listing.get(\"rubric_id\"):\n failures.append(\"complementary_bundle:missing_eval_rubric\")\n\n quality_path = bundle / \"QUALITY_REPORT.md\"\n quality_metric_present = any(\n listing.get(\"quality\", {}).get(metric) is not None\n for metric in (\"benchmark_pass_rate\", \"benchmark_difficulty_score\")\n )\n if not quality_path.exists() or not quality_metric_present:\n failures.append(\"complementary_bundle:missing_benchmark_evidence\")\n\n return failures","instruction":"Explain the role of `def verify_complementary_bundle(release_dir: str | Path, listing: dict[str, Any]) -> list[str]` in Primitive Foundry.","output":"`verify_complementary_bundle` is a function in `primitive_foundry.commercial`. It belongs to the release, marketplace, commercial, dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.commercial.verify_complementary_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial._lookup_path::explain","input":"Module: primitive_foundry.commercial\nDomains: commercial\nSource path: primitive_foundry/commercial.py\n\ndef _lookup_path(payload: dict[str, Any], dotted: str) -> Any:\n node: Any = payload\n for part in dotted.split(\".\"):\n if not isinstance(node, dict) or part not in node:\n return None\n node = node[part]\n return node","instruction":"Explain the role of `def _lookup_path(payload: dict[str, Any], dotted: str) -> Any` in Primitive Foundry.","output":"`_lookup_path` is a function in `primitive_foundry.commercial`. It belongs to the commercial area of Primitive Foundry.","source_id":"primitive_foundry.commercial._lookup_path","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.build_ftc_claims_matrix::explain","input":"Module: primitive_foundry.commercial\nDomains: release, commercial, compliance\nSource path: primitive_foundry/commercial.py\n\ndef build_ftc_claims_matrix(release_dir: str | Path, listing: dict[str, Any]) -> dict[str, Any]:\n \"\"\"Produce a per-metric evidence matrix for FTC \u00a75 compliance.\n\n For every numeric metric claimed in the listing we record:\n - the metric name and the listing path it came from\n - whether the bundle contains the evidence that backs it\n - the sha256 of the evidence artifact (the metric_evidence_hash)\n\n The matrix is what reviewers and procurement readers inspect when\n judging whether a \"97% pass rate\" claim is supportable. The matrix is\n a verification artifact only \u2014 it does not change listing semantics.\n \"\"\"\n\n directory = Path(release_dir)\n bundle = directory / \"bundle\"\n matrix: list[dict[str, Any]] = []\n for metric_name, dotted in CLAIMED_METRIC_PATHS:\n value = _lookup_path(listing, dotted)\n if value is None:\n continue\n evidence_path = bundle / \"QUALITY_REPORT.md\"\n provenance_path = bundle / \"PROVENANCE_MANIFEST.json\"\n evidence_present = evidence_path.exists()\n provenance_present = provenance_path.exists()\n evidence_hash = \"\"\n if evidence_present:\n evidence_hash = sha256_json({\"file\": evidence_path.name, \"size\": evidence_path.stat().st_size})\n matrix.append(\n {\n \"metric\": metric_name,\n \"listing_path\": dotted,\n \"claimed_value\": value,\n \"evidence_artifact\": \"bundle/QUALITY_REPORT.md\",\n \"evidence_present\": evidence_present,\n \"provenance_present\": provenance_present,\n \"metric_evidence_hash\": evidence_hash,\n }\n )\n return {\n \"manifest_type\": \"ftc_claims_matrix\",\n \"schema_version\": 1,\n \"release_dir\": str(directory),\n \"release_id\": listing.get(\"release_id\"),\n \"claims\": matrix,\n \"all_claims_have_evidence\": all(item[\"evidence_present\"] for item in matrix) if matrix else True,\n }","instruction":"Explain the role of `def build_ftc_claims_matrix(release_dir: str | Path, listing: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_ftc_claims_matrix` is a function in `primitive_foundry.commercial`. It belongs to the release, commercial, compliance area of Primitive Foundry.","source_id":"primitive_foundry.commercial.build_ftc_claims_matrix","task":"python_symbol_explanation"} {"id":"primitive_foundry.commercial.verify_card_accuracy::explain","input":"Module: primitive_foundry.commercial\nDomains: release, commercial\nSource path: primitive_foundry/commercial.py\n\ndef verify_card_accuracy(release_dir: str | Path, listing: dict[str, Any]) -> list[str]:\n matrix = build_ftc_claims_matrix(release_dir, listing)\n failures: list[str] = []\n for claim in matrix[\"claims\"]:\n if not claim[\"evidence_present\"]:\n failures.append(f\"ftc_claims:missing_evidence_for:{claim['metric']}\")\n if not claim[\"metric_evidence_hash\"]:\n failures.append(f\"ftc_claims:missing_evidence_hash_for:{claim['metric']}\")\n # If the listing claims a numeric metric that is not in our known set,\n # surface that as well \u2014 buyers should never see unverifiable numbers.\n quality_block = listing.get(\"quality\", {}) or {}\n known = {name for name, _ in CLAIMED_METRIC_PATHS}\n economics = quality_block.get(\"product_economics\", {}) or {}\n for key, value in {**quality_block, **economics}.items():\n if isinstance(value, bool): # bool is a subclass of int; treat separately\n continue\n if isinstance(value, (int, float)) and key not in known:\n failures.append(f\"ftc_claims:unverifiable_metric:{key}\")\n return failures","instruction":"Explain the role of `def verify_card_accuracy(release_dir: str | Path, listing: dict[str, Any]) -> list[str]` in Primitive Foundry.","output":"`verify_card_accuracy` is a function in `primitive_foundry.commercial`. It belongs to the release, commercial area of Primitive Foundry.","source_id":"primitive_foundry.commercial.verify_card_accuracy","task":"python_symbol_explanation"} {"id":"primitive_foundry.compare.load_report::explain","input":"Module: primitive_foundry.compare\nDomains: foundry\nSource path: primitive_foundry/compare.py\n\ndef load_report(path: str | Path) -> dict[str, Any]:\n with Path(path).open(\"r\", encoding=\"utf-8\") as handle:\n return json.load(handle)","instruction":"Explain the role of `def load_report(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`load_report` is a function in `primitive_foundry.compare`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.compare.load_report","task":"python_symbol_explanation"} {"id":"primitive_foundry.compare.compare_reports::explain","input":"Module: primitive_foundry.compare\nDomains: router\nSource path: primitive_foundry/compare.py\n\ndef compare_reports(before_path: str | Path, after_path: str | Path) -> dict[str, Any]:\n before = load_report(before_path)\n after = load_report(after_path)\n before_results = {item[\"record_id\"]: item for item in before[\"results\"]}\n after_results = {item[\"record_id\"]: item for item in after[\"results\"]}\n shared_ids = sorted(set(before_results).intersection(after_results))\n\n regressions = []\n improvements = []\n changed_routes = []\n for record_id in shared_ids:\n before_item = before_results[record_id]\n after_item = after_results[record_id]\n if before_item[\"passed\"] and not after_item[\"passed\"]:\n regressions.append(record_id)\n if not before_item[\"passed\"] and after_item[\"passed\"]:\n improvements.append(record_id)\n if before_item[\"selected_cell_id\"] != after_item[\"selected_cell_id\"]:\n changed_routes.append(\n {\n \"record_id\": record_id,\n \"before\": before_item[\"selected_cell_id\"],\n \"after\": after_item[\"selected_cell_id\"],\n \"expected\": after_item[\"expected_cell_id\"],\n }\n )\n\n metric_delta = {}\n for name, after_value in after[\"metrics\"].items():\n before_value = before[\"metrics\"].get(name)\n if before_value is not None:\n metric_delta[name] = after_value - before_value\n\n return {\n \"before\": str(before_path),\n \"after\": str(after_path),\n \"before_router\": before.get(\"router\"),\n \"after_router\": after.get(\"router\"),\n \"shared_records\": len(shared_ids),\n \"before_pass_rate\": before[\"pass_rate\"],\n \"after_pass_rate\": after[\"pass_rate\"],\n \"pass_rate_delta\": after[\"pass_rate\"] - before[\"pass_rate\"],\n \"metric_delta\": metric_delta,\n \"regressions\": regressions,\n \"improvements\": improvements,\n \"changed_routes\": changed_routes,\n }","instruction":"Explain the role of `def compare_reports(before_path: str | Path, after_path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`compare_reports` is a function in `primitive_foundry.compare`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.compare.compare_reports","task":"python_symbol_explanation"} {"id":"primitive_foundry.compliance.aggregate.build_compliance_matrix::explain","input":"Module: primitive_foundry.compliance.aggregate\nDomains: release, commercial, license, compliance, source_card\nSource path: primitive_foundry/compliance/aggregate.py\n\ndef build_compliance_matrix(\n *,\n listing: dict[str, Any],\n source_cards: list[dict[str, Any]] | None = None,\n) -> dict[str, Any]:\n source_license_matrix = build_source_license_matrix(\n source_cards=source_cards or [],\n release_license=str(listing.get(\"license\") or \"private-commercial-evaluation\"),\n )\n ear = build_ear_classification(listing=listing, source_cards=source_cards or [])\n state_ai = build_state_ai_posture(listing)\n retention = build_retention_policy(listing)\n bias = build_bias_assessment(listing)\n return {\n \"manifest_type\": \"compliance_matrix\",\n \"schema_version\": 1,\n \"release_id\": listing.get(\"release_id\"),\n \"family\": listing.get(\"family\"),\n \"license\": listing.get(\"license\"),\n \"source_license_matrix\": source_license_matrix,\n \"ear_classification\": ear,\n \"state_ai_posture\": state_ai,\n \"retention_policy\": retention,\n \"bias_assessment\": bias,\n \"all_source_licenses_compatible\": source_license_matrix[\"all_sources_compatible\"],\n }","instruction":"Explain the role of `def build_compliance_matrix(*, listing: dict[str, Any], source_cards: list[dict[str, Any]] | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`build_compliance_matrix` is a function in `primitive_foundry.compliance.aggregate`. It belongs to the release, commercial, license, compliance, source_card area of Primitive Foundry.","source_id":"primitive_foundry.compliance.aggregate.build_compliance_matrix","task":"python_symbol_explanation"} {"id":"primitive_foundry.compliance.aggregate.write_compliance_matrix::explain","input":"Module: primitive_foundry.compliance.aggregate\nDomains: release, compliance, atomic_write, source_card\nSource path: primitive_foundry/compliance/aggregate.py\n\ndef write_compliance_matrix(\n *,\n release_dir: str | Path,\n listing: dict[str, Any],\n source_cards: list[dict[str, Any]] | None = None,\n) -> Path:\n directory = Path(release_dir)\n payload = build_compliance_matrix(listing=listing, source_cards=source_cards)\n target = directory / \"COMPLIANCE_MATRIX.json\"\n locked_atomic_write_json(target, payload)\n return target","instruction":"Explain the role of `def write_compliance_matrix(*, release_dir: str | Path, listing: dict[str, Any], source_cards: list[dict[str, Any]] | None=None) -> Path` in Primitive Foundry.","output":"`write_compliance_matrix` is a function in `primitive_foundry.compliance.aggregate`. It belongs to the release, compliance, atomic_write, source_card area of Primitive Foundry.","source_id":"primitive_foundry.compliance.aggregate.write_compliance_matrix","task":"python_symbol_explanation"} {"id":"primitive_foundry.compliance.bias_assessment.build_bias_assessment::explain","input":"Module: primitive_foundry.compliance.bias_assessment\nDomains: dataset, compliance\nSource path: primitive_foundry/compliance/bias_assessment.py\n\ndef build_bias_assessment(listing: dict[str, Any]) -> dict[str, Any]:\n family = str(listing.get(\"family\") or \"\")\n relevant = family in BIAS_RELEVANT_FAMILIES\n overrides = listing.get(\"bias_assessment_overrides\") or {}\n return {\n \"manifest_type\": \"bias_assessment\",\n \"schema_version\": 1,\n \"family\": family,\n \"applicability\": \"in_scope\" if relevant else \"not_applicable\",\n \"demographic_coverage_statement\": str(\n overrides.get(\"demographic_coverage_statement\")\n or (\n \"Records are derived from regulatory text and synthetic agent traces; \"\n \"no protected-class human attributes are encoded.\"\n if not relevant\n else \"Records describe agent-runtime scenarios; demographic coverage is not directly \"\n \"encoded. Buyers integrating outputs in employment, lending, or health contexts \"\n \"must perform their own bias audit before deployment.\"\n )\n ),\n \"known_limitations\": list(\n overrides.get(\"known_limitations\")\n or [\n \"Records reflect English-language regulatory and procedural language only.\",\n \"No guarantee that buyer-side deployments will retain bias-free properties.\",\n ]\n ),\n \"suggested_mitigations\": list(\n overrides.get(\"suggested_mitigations\")\n or [\n \"Buyer should run an internal bias audit on any model trained or evaluated against this dataset.\",\n \"Buyer should retain the right to flag and quarantine outputs that surface protected-class disparities.\",\n ]\n ),\n \"performed_by\": str(overrides.get(\"performed_by\") or \"Primitive Origins LLC (founder-attested)\"),\n \"performed_at\": str(overrides.get(\"performed_at\") or listing.get(\"created_at\") or \"\"),\n }","instruction":"Explain the role of `def build_bias_assessment(listing: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_bias_assessment` is a function in `primitive_foundry.compliance.bias_assessment`. It belongs to the dataset, compliance area of Primitive Foundry.","source_id":"primitive_foundry.compliance.bias_assessment.build_bias_assessment","task":"python_symbol_explanation"} {"id":"primitive_foundry.compliance.ear.refuse_itar::explain","input":"Module: primitive_foundry.compliance.ear\nDomains: release, compliance\nSource path: primitive_foundry/compliance/ear.py\n\ndef refuse_itar(claimed: str | None) -> None:\n if (claimed or \"\").strip().lower() in REFUSED_CLASSIFICATIONS:\n raise ValueError(\n \"ITAR-classified source material cannot appear in a Foundry release. \"\n \"Refused before listing per export-controls policy.\"\n )","instruction":"Explain the role of `def refuse_itar(claimed: str | None) -> None` in Primitive Foundry.","output":"`refuse_itar` is a function in `primitive_foundry.compliance.ear`. It belongs to the release, compliance area of Primitive Foundry.","source_id":"primitive_foundry.compliance.ear.refuse_itar","task":"python_symbol_explanation"} {"id":"primitive_foundry.compliance.ear.build_ear_classification::explain","input":"Module: primitive_foundry.compliance.ear\nDomains: release, compliance, source_card\nSource path: primitive_foundry/compliance/ear.py\n\ndef build_ear_classification(\n *,\n listing: dict[str, Any],\n source_cards: list[dict[str, Any]] | None = None,\n) -> dict[str, Any]:\n declared = (listing.get(\"export_classification\") or EXPORT_CLASSIFICATION_DEFAULT).strip().lower()\n refuse_itar(declared)\n if declared not in ALLOWED_CLASSIFICATIONS:\n declared = EXPORT_CLASSIFICATION_DEFAULT\n per_source = []\n for card in source_cards or []:\n metadata = card.get(\"metadata\") or {}\n source_class = (metadata.get(\"export_classification\") or EXPORT_CLASSIFICATION_DEFAULT).strip().lower()\n refuse_itar(source_class)\n per_source.append(\n {\n \"source_id\": str(card.get(\"source_id\") or card.get(\"id\") or \"\"),\n \"export_classification\": source_class,\n }\n )\n return {\n \"manifest_type\": \"ear_classification\",\n \"schema_version\": 1,\n \"release_classification\": declared,\n \"per_source_classification\": per_source,\n \"itar_refused\": True,\n }","instruction":"Explain the role of `def build_ear_classification(*, listing: dict[str, Any], source_cards: list[dict[str, Any]] | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`build_ear_classification` is a function in `primitive_foundry.compliance.ear`. It belongs to the release, compliance, source_card area of Primitive Foundry.","source_id":"primitive_foundry.compliance.ear.build_ear_classification","task":"python_symbol_explanation"} {"id":"primitive_foundry.compliance.retention.build_retention_policy::explain","input":"Module: primitive_foundry.compliance.retention\nDomains: release, compliance\nSource path: primitive_foundry/compliance/retention.py\n\ndef build_retention_policy(listing: dict[str, Any]) -> dict[str, Any]:\n years = int(listing.get(\"retention_years\") or DEFAULT_RETENTION_YEARS)\n return {\n \"manifest_type\": \"retention_policy\",\n \"schema_version\": 1,\n \"retention_years\": years,\n \"policy_text\": (\n f\"Source files referenced by this release are hashed and stored locally on the seller \"\n f\"machine for {years} years for audit and provenance verification. Source files are \"\n \"never shared with the buyer or any third party. Only sterilized, derived records \"\n \"appear in the released bundle. After the retention period elapses, the seller may \"\n \"discard source files at their discretion; the released bundle is unaffected.\"\n ),\n \"source_files_shared_with_buyer\": False,\n \"buyer_receives_derived_records_only\": True,\n }","instruction":"Explain the role of `def build_retention_policy(listing: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_retention_policy` is a function in `primitive_foundry.compliance.retention`. It belongs to the release, compliance area of Primitive Foundry.","source_id":"primitive_foundry.compliance.retention.build_retention_policy","task":"python_symbol_explanation"} {"id":"primitive_foundry.compliance.source_licenses.normalise::explain","input":"Module: primitive_foundry.compliance.source_licenses\nDomains: license, compliance\nSource path: primitive_foundry/compliance/source_licenses.py\n\ndef normalise(value: str | None) -> str:\n return (value or \"\").strip().lower()","instruction":"Explain the role of `def normalise(value: str | None) -> str` in Primitive Foundry.","output":"`normalise` is a function in `primitive_foundry.compliance.source_licenses`. It belongs to the license, compliance area of Primitive Foundry.","source_id":"primitive_foundry.compliance.source_licenses.normalise","task":"python_symbol_explanation"} {"id":"primitive_foundry.compliance.source_licenses.build_source_license_matrix::explain","input":"Module: primitive_foundry.compliance.source_licenses\nDomains: release, license, compliance, source_card\nSource path: primitive_foundry/compliance/source_licenses.py\n\ndef build_source_license_matrix(\n *,\n source_cards: list[dict[str, Any]],\n release_license: str,\n) -> dict[str, Any]:\n \"\"\"Aggregate per-source license declarations into one matrix.\n\n Each source card is expected to carry a `metadata.source_license`\n string. The matrix lists every source license seen and flags any pair\n that is incompatible with the declared release license.\n \"\"\"\n\n release = normalise(release_license)\n seen_licenses: dict[str, int] = {}\n incompatibilities: list[dict[str, str]] = []\n for card in source_cards:\n metadata = card.get(\"metadata\") or {}\n source_license = normalise(metadata.get(\"source_license\"))\n if not source_license:\n source_license = \"unspecified\"\n seen_licenses[source_license] = seen_licenses.get(source_license, 0) + 1\n pair = (source_license, release)\n if pair in INCOMPATIBLE_LICENSE_PAIRS:\n incompatibilities.append(\n {\n \"source_id\": str(card.get(\"source_id\") or card.get(\"id\") or \"\"),\n \"source_license\": source_license,\n \"release_license\": release,\n \"reason\": \"license-pair-flagged-incompatible\",\n }\n )\n return {\n \"manifest_type\": \"source_license_matrix\",\n \"schema_version\": 1,\n \"release_license\": release,\n \"source_license_counts\": seen_licenses,\n \"incompatibilities\": incompatibilities,\n \"all_sources_compatible\": not incompatibilities,\n \"unspecified_count\": seen_licenses.get(\"unspecified\", 0),\n }","instruction":"Explain the role of `def build_source_license_matrix(*, source_cards: list[dict[str, Any]], release_license: str) -> dict[str, Any]` in Primitive Foundry.","output":"`build_source_license_matrix` is a function in `primitive_foundry.compliance.source_licenses`. It belongs to the release, license, compliance, source_card area of Primitive Foundry.","source_id":"primitive_foundry.compliance.source_licenses.build_source_license_matrix","task":"python_symbol_explanation"} {"id":"primitive_foundry.compliance.state_ai.build_state_ai_posture::explain","input":"Module: primitive_foundry.compliance.state_ai\nDomains: compliance\nSource path: primitive_foundry/compliance/state_ai.py\n\ndef build_state_ai_posture(listing: dict[str, Any]) -> dict[str, Any]:\n overrides = listing.get(\"state_ai_overrides\") or {}\n frameworks = []\n for framework in STATE_AI_FRAMEWORKS:\n override = overrides.get(framework[\"framework\"]) or {}\n frameworks.append(\n {\n **framework,\n \"posture\": str(override.get(\"posture\") or framework[\"default_posture\"]),\n \"evidence\": str(override.get(\"evidence\") or \"\"),\n }\n )\n return {\n \"manifest_type\": \"state_ai_posture\",\n \"schema_version\": 1,\n \"frameworks\": frameworks,\n }","instruction":"Explain the role of `def build_state_ai_posture(listing: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_state_ai_posture` is a function in `primitive_foundry.compliance.state_ai`. It belongs to the compliance area of Primitive Foundry.","source_id":"primitive_foundry.compliance.state_ai.build_state_ai_posture","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.load_standing_orders::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef load_standing_orders(path: str | Path | None) -> list[StandingOrder]:\n if path is None:\n return []\n source = Path(path)\n if not source.exists():\n return []\n if source.suffix == \".jsonl\":\n orders = []\n with source.open(\"r\", encoding=\"utf-8\") as handle:\n for index, line in enumerate(handle, start=1):\n stripped = line.strip()\n if not stripped:\n continue\n payload = json.loads(stripped)\n if is_standing_order_event(payload):\n orders.append(StandingOrder.from_dict(payload, index))\n return orders\n payload = json.loads(source.read_text(encoding=\"utf-8\"))\n rows = payload.get(\"standing_orders\", payload if isinstance(payload, list) else [])\n return [StandingOrder.from_dict(row, index) for index, row in enumerate(rows, start=1)]","instruction":"Explain the role of `def load_standing_orders(path: str | Path | None) -> list[StandingOrder]` in Primitive Foundry.","output":"`load_standing_orders` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.load_standing_orders","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.standing_orders_from_bus_events::explain","input":"Module: primitive_foundry.curation_brain\nDomains: bus, curation\nSource path: primitive_foundry/curation_brain.py\n\ndef standing_orders_from_bus_events(events_path: str | Path) -> list[StandingOrder]:\n orders = []\n with Path(events_path).open(\"r\", encoding=\"utf-8\") as handle:\n for index, line in enumerate(handle, start=1):\n stripped = line.strip()\n if not stripped:\n continue\n try:\n payload = json.loads(stripped)\n except json.JSONDecodeError:\n continue\n if is_standing_order_event(payload):\n orders.append(StandingOrder.from_dict(payload, index))\n return orders","instruction":"Explain the role of `def standing_orders_from_bus_events(events_path: str | Path) -> list[StandingOrder]` in Primitive Foundry.","output":"`standing_orders_from_bus_events` is a function in `primitive_foundry.curation_brain`. It belongs to the bus, curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.standing_orders_from_bus_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.is_standing_order_event::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef is_standing_order_event(payload: dict[str, Any]) -> bool:\n event_type = str(payload.get(\"event_type\") or payload.get(\"subject\") or \"\")\n return event_type == STANDING_ORDER_UPSERTED","instruction":"Explain the role of `def is_standing_order_event(payload: dict[str, Any]) -> bool` in Primitive Foundry.","output":"`is_standing_order_event` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.is_standing_order_event","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.write_standing_orders::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation, atomic_write\nSource path: primitive_foundry/curation_brain.py\n\ndef write_standing_orders(path: str | Path, orders: list[StandingOrder]) -> dict[str, Any]:\n payload = {\n \"manifest_type\": \"primitive_foundry_standing_orders\",\n \"schema_version\": 1,\n \"updated_at\": datetime.now(timezone.utc).isoformat(),\n \"standing_orders\": [order.to_dict() for order in orders],\n }\n payload[\"orders_hash\"] = sha256_json({**payload, \"orders_hash\": \"\"})\n atomic_write_json(path, payload)\n return payload","instruction":"Explain the role of `def write_standing_orders(path: str | Path, orders: list[StandingOrder]) -> dict[str, Any]` in Primitive Foundry.","output":"`write_standing_orders` is a function in `primitive_foundry.curation_brain`. It belongs to the curation, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.write_standing_orders","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.plan_curation::explain","input":"Module: primitive_foundry.curation_brain\nDomains: bus, curation, atomic_write\nSource path: primitive_foundry/curation_brain.py\n\ndef plan_curation(\n *,\n events_path: str | Path,\n standing_orders_path: str | Path | None = None,\n output_path: str | Path | None = None,\n min_value_score: float = MEDIUM_VALUE_THRESHOLD,\n classifier: str = \"deterministic\",\n max_opportunities: int = 12,\n llm_advisor: Callable[[dict[str, Any]], dict[str, Any]] | None = None,\n) -> dict[str, Any]:\n rows = read_product_event_rows(events_path)\n standing_orders = load_standing_orders(standing_orders_path) + standing_orders_from_bus_events(events_path)\n classified_rows = []\n invalid_count = 0\n for row in rows:\n if row.event is None:\n invalid_count += 1\n continue\n classification = classify_event_with_mode(row.event, min_value_score=min_value_score, classifier=classifier)\n family = classify_product_family(row.event, classification)\n order_matches = match_standing_orders(row.event, classification, family, standing_orders)\n adjusted_score = adjusted_value_score(classification.value_score, order_matches)\n classified_rows.append(\n {\n \"event\": row.event,\n \"classification\": classification,\n \"family\": family,\n \"standing_order_matches\": order_matches,\n \"adjusted_value_score\": adjusted_score,\n }\n )\n\n family_groups: dict[str, list[dict[str, Any]]] = {}\n for item in classified_rows:\n if item[\"adjusted_value_score\"] < min_value_score:\n continue\n family_groups.setdefault(item[\"family\"], []).append(item)\n\n opportunities = [\n build_opportunity(family, items, standing_orders)\n for family, items in family_groups.items()\n if items\n ]\n opportunities.sort(key=lambda item: (item[\"priority_score\"], item[\"event_count\"]), reverse=True)\n opportunities = opportunities[:max_opportunities]\n research_requests = [request for item in opportunities for request in item[\"research_requests\"]]\n\n advisor_result = _maybe_llm_advisor(\n advisor=llm_advisor,\n opportunities=opportunities,\n standing_orders=standing_orders,\n )\n\n plan = {\n \"manifest_type\": \"primitive_foundry_curation_plan\",\n \"schema_version\": 1,\n \"events_path\": str(events_path),\n \"standing_orders_path\": str(standing_orders_path) if standing_orders_path else None,\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"coordination\": \"event-bus-only\",\n \"direct_agent_call\": False,\n \"local_private_only\": True,\n \"classifier\": classifier,\n \"min_value_score\": min_value_score,\n \"input_event_count\": len([row for row in rows if row.event is not None]),\n \"invalid_count\": invalid_count,\n \"standing_order_count\": len(standing_orders),\n \"opportunities\": opportunities,\n \"research_requests\": research_requests,\n \"llm_advisor\": advisor_result,\n }\n plan[\"plan_hash\"] = sha256_json({**plan, \"plan_hash\": \"\"})\n if output_path:\n atomic_write_json(output_path, plan)\n return plan","instruction":"Explain the role of `def plan_curation(*, events_path: str | Path, standing_orders_path: str | Path | None=None, output_path: str | Path | None=None, min_value_score: float=MEDIUM_VALUE_THRESHOLD, classifier: str='deterministic', max_opportunities: int=12, llm_advisor: Callable[[dict[str, Any]], dict[str, Any]] | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`plan_curation` is a function in `primitive_foundry.curation_brain`. It belongs to the bus, curation, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.plan_curation","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.match_standing_orders::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef match_standing_orders(\n event: ProductEvent,\n classification: ProductClassification,\n family: str,\n standing_orders: list[StandingOrder],\n) -> list[dict[str, Any]]:\n text = searchable_text(event, classification, family)\n matches = []\n for order in standing_orders:\n if order.focus_families and family not in order.focus_families:\n continue\n if order.product_kinds and classification.product_kind not in order.product_kinds:\n continue\n if any(token in text for token in order.banned_keywords):\n continue\n keyword_hits = [token for token in order.keywords if token in text]\n if order.keywords and not keyword_hits:\n continue\n matches.append(\n {\n \"order_id\": order.order_id,\n \"priority\": order.priority,\n \"keyword_hits\": keyword_hits,\n \"research_allowed\": order.research_allowed,\n \"require_complementary_bundle\": order.require_complementary_bundle,\n }\n )\n return matches","instruction":"Explain the role of `def match_standing_orders(event: ProductEvent, classification: ProductClassification, family: str, standing_orders: list[StandingOrder]) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`match_standing_orders` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.match_standing_orders","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.adjusted_value_score::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef adjusted_value_score(base_score: float, order_matches: list[dict[str, Any]]) -> float:\n if not order_matches:\n return base_score\n priority_boost = min(0.12, max(float(match[\"priority\"]) for match in order_matches) / 1000.0)\n keyword_boost = min(0.08, 0.02 * sum(len(match[\"keyword_hits\"]) for match in order_matches))\n return round(min(1.0, base_score + priority_boost + keyword_boost), 4)","instruction":"Explain the role of `def adjusted_value_score(base_score: float, order_matches: list[dict[str, Any]]) -> float` in Primitive Foundry.","output":"`adjusted_value_score` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.adjusted_value_score","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.build_opportunity::explain","input":"Module: primitive_foundry.curation_brain\nDomains: sterilization, release, curation, dataset, benchmark\nSource path: primitive_foundry/curation_brain.py\n\ndef build_opportunity(family: str, items: list[dict[str, Any]], standing_orders: list[StandingOrder]) -> dict[str, Any]:\n items = sorted(items, key=lambda item: item[\"adjusted_value_score\"], reverse=True)\n product_mix = {kind: 0 for kind in PRODUCT_KINDS}\n for item in items:\n product_mix[item[\"classification\"].product_kind] += 1\n missing = complementary_missing(product_mix)\n matched_order_ids = sorted(\n {\n match[\"order_id\"]\n for item in items\n for match in item[\"standing_order_matches\"]\n }\n )\n evidence = [event_evidence(item) for item in items[:10]]\n priority_score = round(\n sum(item[\"adjusted_value_score\"] for item in items) / max(1, len(items))\n + min(0.25, 0.03 * len(items))\n + (0.12 if matched_order_ids else 0.0)\n + (0.08 if not missing else 0.0),\n 4,\n )\n research_requests = []\n if missing and any(order.research_allowed for order in standing_orders if order.order_id in matched_order_ids):\n research_requests.append(build_market_research_request(family, missing, matched_order_ids, evidence))\n return {\n \"family\": family,\n \"title\": family_title(family),\n \"category\": FAMILY_REGISTRY.get(family).category if family in FAMILY_REGISTRY else \"dataset\",\n \"priority_score\": priority_score,\n \"event_count\": len(items),\n \"recommended_action\": \"build_bundle\" if not missing else \"curate_more_complementary_inputs\",\n \"product_mix\": product_mix,\n \"missing_complementary_kinds\": missing,\n \"standing_order_ids\": matched_order_ids,\n \"evidence\": evidence,\n \"card_accuracy_gates\": [\n \"source_path_exists\",\n \"source_hash_bound\",\n \"sterilization_passed_before_release\",\n \"dataset_eval_benchmark_family_alignment\",\n \"human_or_local_review_before_external_listing\",\n ],\n \"research_requests\": research_requests,\n }","instruction":"Explain the role of `def build_opportunity(family: str, items: list[dict[str, Any]], standing_orders: list[StandingOrder]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_opportunity` is a function in `primitive_foundry.curation_brain`. It belongs to the sterilization, release, curation, dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.build_opportunity","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.complementary_missing::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation, dataset, benchmark\nSource path: primitive_foundry/curation_brain.py\n\ndef complementary_missing(product_mix: dict[str, int]) -> list[str]:\n if product_mix[\"dataset\"] == 0:\n return [\"dataset\"]\n missing = []\n if product_mix[\"eval_harness\"] == 0:\n missing.append(\"eval_harness\")\n if product_mix[\"benchmark\"] == 0:\n missing.append(\"benchmark\")\n return missing","instruction":"Explain the role of `def complementary_missing(product_mix: dict[str, int]) -> list[str]` in Primitive Foundry.","output":"`complementary_missing` is a function in `primitive_foundry.curation_brain`. It belongs to the curation, dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.complementary_missing","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.build_market_research_request::explain","input":"Module: primitive_foundry.curation_brain\nDomains: bus, curation\nSource path: primitive_foundry/curation_brain.py\n\ndef build_market_research_request(\n family: str,\n missing: list[str],\n standing_order_ids: list[str],\n evidence: list[dict[str, Any]],\n) -> dict[str, Any]:\n return {\n \"event_type\": MARKET_RESEARCH_REQUESTED,\n \"source\": \"primitive_foundry.curation_brain\",\n \"payload\": {\n \"schema_version\": 1,\n \"coordination\": \"event-bus-only\",\n \"direct_agent_call\": False,\n \"direct_user_notification\": False,\n \"local_private_only\": True,\n \"external_lookup_allowed\": False,\n \"approval_required_before_network\": True,\n \"requested_tool_family\": \"firecrawl\",\n \"family\": family,\n \"missing_product_kinds\": missing,\n \"standing_order_ids\": standing_order_ids,\n \"question\": (\n f\"Locally assess whether {family_title(family)} should be expanded with \"\n f\"{', '.join(missing)} artifacts and identify buyer-facing claims needing evidence.\"\n ),\n \"evidence_event_ids\": [item[\"event_id\"] for item in evidence],\n },\n }","instruction":"Explain the role of `def build_market_research_request(family: str, missing: list[str], standing_order_ids: list[str], evidence: list[dict[str, Any]]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_market_research_request` is a function in `primitive_foundry.curation_brain`. It belongs to the bus, curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.build_market_research_request","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.event_evidence::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef event_evidence(item: dict[str, Any]) -> dict[str, Any]:\n event: ProductEvent = item[\"event\"]\n classification: ProductClassification = item[\"classification\"]\n source = Path(event.source_path).expanduser()\n return {\n \"event_id\": event.event_id,\n \"source_path\": event.source_path,\n \"source_exists\": source.exists(),\n \"source_id\": event.source_id,\n \"source_hash\": sha256_json({\"source_path\": event.source_path, \"source_id\": event.source_id}),\n \"product_kind\": classification.product_kind,\n \"domain_path\": classification.domain_path,\n \"value_score\": classification.value_score,\n \"adjusted_value_score\": item[\"adjusted_value_score\"],\n \"reasons\": classification.reasons,\n }","instruction":"Explain the role of `def event_evidence(item: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`event_evidence` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.event_evidence","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.searchable_text::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef searchable_text(event: ProductEvent, classification: ProductClassification, family: str) -> str:\n return \" \".join(\n [\n event.text,\n \" \".join(event.tags),\n json.dumps(event.metadata, sort_keys=True),\n classification.product_kind,\n classification.domain_path,\n family,\n ]\n ).lower()","instruction":"Explain the role of `def searchable_text(event: ProductEvent, classification: ProductClassification, family: str) -> str` in Primitive Foundry.","output":"`searchable_text` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.searchable_text","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.infer_missing_product_kind::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef infer_missing_product_kind(text: str) -> str:\n return max(PRODUCT_KINDS, key=lambda item: keyword_score(text, KIND_KEYWORDS[item]))","instruction":"Explain the role of `def infer_missing_product_kind(text: str) -> str` in Primitive Foundry.","output":"`infer_missing_product_kind` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.infer_missing_product_kind","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain._default_probe::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef _default_probe(endpoint: str) -> bool:\n try:\n from urllib import request\n\n with request.urlopen(f\"{endpoint.rstrip('/')}/api/tags\", timeout=1.5) as response:\n return response.status == 200\n except Exception:\n return False","instruction":"Explain the role of `def _default_probe(endpoint: str) -> bool` in Primitive Foundry.","output":"`_default_probe` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain._default_probe","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain._maybe_llm_advisor::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef _maybe_llm_advisor(\n *,\n advisor: Callable[[dict[str, Any]], dict[str, Any]] | None,\n opportunities: list[dict[str, Any]],\n standing_orders: list[StandingOrder],\n) -> dict[str, Any]:\n if not opportunities:\n return {\"status\": \"skipped\", \"reason\": \"no_opportunities\"}\n if advisor is None and not llm_advisor_available():\n return {\"status\": \"disabled\"}\n if advisor is None:\n advisor = _default_llm_advisor\n\n summary = _opportunity_summary(opportunities, standing_orders)\n try:\n raw = advisor(summary)\n except Exception as exc:\n return {\"status\": \"errored\", \"error_class\": exc.__class__.__name__, \"error_message\": str(exc)}\n\n return _normalise_advisor_response(raw, opportunities)","instruction":"Explain the role of `def _maybe_llm_advisor(*, advisor: Callable[[dict[str, Any]], dict[str, Any]] | None, opportunities: list[dict[str, Any]], standing_orders: list[StandingOrder]) -> dict[str, Any]` in Primitive Foundry.","output":"`_maybe_llm_advisor` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain._maybe_llm_advisor","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain._opportunity_summary::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation\nSource path: primitive_foundry/curation_brain.py\n\ndef _opportunity_summary(\n opportunities: list[dict[str, Any]],\n standing_orders: list[StandingOrder],\n) -> dict[str, Any]:\n return {\n \"opportunities\": [\n {\n \"family\": item[\"family\"],\n \"title\": item[\"title\"],\n \"category\": item[\"category\"],\n \"priority_score\": item[\"priority_score\"],\n \"event_count\": item[\"event_count\"],\n \"recommended_action\": item[\"recommended_action\"],\n \"product_mix\": item[\"product_mix\"],\n \"missing_complementary_kinds\": item[\"missing_complementary_kinds\"],\n \"standing_order_ids\": item[\"standing_order_ids\"],\n }\n for item in opportunities\n ],\n \"standing_orders\": [\n {\n \"order_id\": order.order_id,\n \"priority\": order.priority,\n \"focus_families\": list(order.focus_families),\n \"product_kinds\": list(order.product_kinds),\n \"research_allowed\": order.research_allowed,\n }\n for order in standing_orders\n ],\n }","instruction":"Explain the role of `def _opportunity_summary(opportunities: list[dict[str, Any]], standing_orders: list[StandingOrder]) -> dict[str, Any]` in Primitive Foundry.","output":"`_opportunity_summary` is a function in `primitive_foundry.curation_brain`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain._opportunity_summary","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain._default_llm_advisor::explain","input":"Module: primitive_foundry.curation_brain\nDomains: curation, dataset, benchmark\nSource path: primitive_foundry/curation_brain.py\n\ndef _default_llm_advisor(summary: dict[str, Any]) -> dict[str, Any]:\n from urllib import request\n\n endpoint = os.environ.get(LLM_ENDPOINT_ENV_VAR, DEFAULT_LLM_ENDPOINT)\n model = os.environ.get(LLM_MODEL_ENV_VAR, DEFAULT_LLM_MODEL)\n prompt = (\n \"You are a Foundry curation advisor. Given the JSON summary of \"\n \"candidate dataset/eval/benchmark opportunities and any active \"\n \"standing orders, return STRICT JSON with these keys:\\n\"\n \" ranked_families: list of {family, rationale, complementary_kinds_to_add, recommend_research}\\n\"\n \" bundle_proposals: list of {family, composition, complementary, rationale}\\n\"\n \" advisor_notes: short string\\n\"\n \"Rules: composition must use only ['dataset','eval_harness','benchmark']. \"\n \"A complementary bundle has at least one of each. Never invent families \"\n \"that aren't present in opportunities. Prefer bundles that satisfy active \"\n \"standing orders. Reply with a single JSON object, no prose.\\n\\n\"\n \"SUMMARY:\\n\"\n ) + json.dumps(summary, sort_keys=True)\n body = json.dumps(\n {\n \"model\": model,\n \"prompt\": prompt,\n \"stream\": False,\n \"format\": \"json\",\n \"options\": {\"temperature\": 0, \"num_predict\": 1024},\n }\n ).encode(\"utf-8\")\n req = request.Request(\n f\"{endpoint.rstrip('/')}/api/generate\",\n data=body,\n headers={\"Content-Type\": \"application/json\"},\n )\n with request.urlopen(req, timeout=60) as response:\n data = json.loads(response.read())\n raw = str(data.get(\"response\") or \"{}\").strip()\n try:\n return json.loads(raw)\n except json.JSONDecodeError:\n return {}","instruction":"Explain the role of `def _default_llm_advisor(summary: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`_default_llm_advisor` is a function in `primitive_foundry.curation_brain`. It belongs to the curation, dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain._default_llm_advisor","task":"python_symbol_explanation"} {"id":"primitive_foundry.curation_brain.classify_product_family::explain","input":"Module: primitive_foundry.curation_brain\nDomains: sterilization, privacy, marketplace, license, planner, curation, dataset, router, benchmark\nSource path: primitive_foundry/curation_brain.py\n\ndef classify_product_family(event: ProductEvent, classification: ProductClassification) -> str:\n text = \" \".join([event.text, \" \".join(event.tags), json.dumps(event.metadata, sort_keys=True)]).lower()\n for tag in event.tags:\n if tag in FAMILY_REGISTRY and not FAMILY_REGISTRY[tag].legacy and tag not in {\"dataset\", \"eval_harness\", \"benchmark\"}:\n return tag\n metadata_family = event.metadata.get(\"dataset_family\") or event.metadata.get(\"source_family\") or event.metadata.get(\"planner_family\")\n if metadata_family in FAMILY_REGISTRY and not FAMILY_REGISTRY[metadata_family].legacy:\n return str(metadata_family)\n if any(token in text for token in (\"privacy\", \"provenance\", \"sterilization\", \"license\")):\n return \"privacy_provenance_eval\"\n if any(token in text for token in (\"agent\", \"trace\", \"trajectory\", \"tool call\", \"governance\", \"override\")):\n return \"agent_runtime_governance\"\n if any(token in text for token in (\"lifecycle\", \"apoptosis\", \"replacement\", \"stale\", \"retired\", \"repair\")):\n return \"verified_agentic_build\"\n if any(token in text for token in (\"router\", \"embedding\", \"nomic\", \"classifier\", \"training\")):\n return \"router_training\"\n if any(token in text for token in (\"marketplace\", \"buyer\", \"sale\", \"pricing\", \"commerce\")):\n return \"marketplace_bundle\"\n return classification.product_kind","instruction":"Explain the role of `def classify_product_family(event: ProductEvent, classification: ProductClassification) -> str` in Primitive Foundry.","output":"`classify_product_family` is a function in `primitive_foundry.curation_brain`. It belongs to the sterilization, privacy, marketplace, license, planner, curation, dataset, router, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.curation_brain.classify_product_family","task":"python_symbol_explanation"} {"id":"primitive_foundry.dataset.load_jsonl::explain","input":"Module: primitive_foundry.dataset\nDomains: dataset\nSource path: primitive_foundry/dataset.py\n\ndef load_jsonl(path: str | Path) -> list[FoundryRecord]:\n dataset_path = Path(path)\n records: list[FoundryRecord] = []\n\n with dataset_path.open(\"r\", encoding=\"utf-8\") as handle:\n for line_number, line in enumerate(handle, start=1):\n stripped = line.strip()\n if not stripped:\n continue\n try:\n payload = json.loads(stripped)\n records.append(FoundryRecord.from_dict(payload))\n except Exception as exc:\n raise ValueError(f\"Invalid Foundry JSONL at {dataset_path}:{line_number}: {exc}\") from exc\n\n if not records:\n raise ValueError(f\"No Foundry records found in {dataset_path}\")\n validate_records(records)\n return records","instruction":"Explain the role of `def load_jsonl(path: str | Path) -> list[FoundryRecord]` in Primitive Foundry.","output":"`load_jsonl` is a function in `primitive_foundry.dataset`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.dataset.load_jsonl","task":"python_symbol_explanation"} {"id":"primitive_foundry.dataset.iter_by_task::explain","input":"Module: primitive_foundry.dataset\nDomains: dataset\nSource path: primitive_foundry/dataset.py\n\ndef iter_by_task(records: Iterable[FoundryRecord], task: str) -> list[FoundryRecord]:\n return [record for record in records if record.task == task]","instruction":"Explain the role of `def iter_by_task(records: Iterable[FoundryRecord], task: str) -> list[FoundryRecord]` in Primitive Foundry.","output":"`iter_by_task` is a function in `primitive_foundry.dataset`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.dataset.iter_by_task","task":"python_symbol_explanation"} {"id":"primitive_foundry.dataset.validate_records::explain","input":"Module: primitive_foundry.dataset\nDomains: license, curation, dataset\nSource path: primitive_foundry/dataset.py\n\ndef validate_records(records: list[FoundryRecord]) -> None:\n seen_ids: set[str] = set()\n for record in records:\n if record.record_id in seen_ids:\n raise ValueError(f\"Duplicate record_id: {record.record_id}\")\n seen_ids.add(record.record_id)\n\n if record.task not in ALLOWED_TASKS:\n raise ValueError(f\"{record.record_id}: unknown task {record.task}\")\n if \".\" not in record.domain_path:\n raise ValueError(f\"{record.record_id}: domain_path must be dotted\")\n if not record.expected_cell_id.startswith(f\"{record.domain_path}.\"):\n raise ValueError(f\"{record.record_id}: expected_cell_id must match domain_path\")\n if record.source_type not in {\"synthetic\", \"private-curated\"}:\n raise ValueError(f\"{record.record_id}: unsupported source_type {record.source_type}\")\n if record.license not in {\"private-synthetic\", \"private-internal\"}:\n raise ValueError(f\"{record.record_id}: unsupported license {record.license}\")\n if record.source_type == \"private-curated\":\n for key in (\"source_id\", \"source_hash\", \"source_path\", \"curation_method\"):\n if not record.metadata.get(key):\n raise ValueError(f\"{record.record_id}: private-curated record requires metadata.{key}\")\n if record.task in {\n \"detect_stale_cell\",\n \"replace_cell_without_global_retrain\",\n \"resolve_old_new_conflict\",\n \"apoptosis_event_replay\",\n }:\n if not record.stale_cell_id:\n raise ValueError(f\"{record.record_id}: task requires stale_cell_id\")\n if not record.replacement_for:\n raise ValueError(f\"{record.record_id}: task requires replacement_for\")\n if record.task == \"multi_cell_routing\" and len(record.expected_cell_ids) < 2:\n raise ValueError(f\"{record.record_id}: multi_cell_routing requires at least two expected cells\")","instruction":"Explain the role of `def validate_records(records: list[FoundryRecord]) -> None` in Primitive Foundry.","output":"`validate_records` is a function in `primitive_foundry.dataset`. It belongs to the license, curation, dataset area of Primitive Foundry.","source_id":"primitive_foundry.dataset.validate_records","task":"python_symbol_explanation"} {"id":"primitive_foundry.delivery.__init__.write_delivery_shapes::explain","input":"Module: primitive_foundry.delivery.__init__\nDomains: release\nSource path: primitive_foundry/delivery/__init__.py\n\ndef write_delivery_shapes(release_dir: str | Path, shapes: list[str]) -> dict[str, Any]:\n release = Path(release_dir)\n bundle = release / \"bundle\"\n output_root = release / \"delivery\"\n output_root.mkdir(parents=True, exist_ok=True)\n written = {}\n for shape in shapes:\n normalized = shape.strip().lower()\n if not normalized:\n continue\n if normalized == \"tar_gz\":\n written[normalized] = write_tar_gz_bundle(bundle, output_root / \"tar_gz\")\n elif normalized == \"parquet\":\n written[normalized] = write_parquet_bundle(bundle / \"source_foundry_records.jsonl\", output_root / \"parquet\")\n elif normalized == \"delta\":\n written[normalized] = write_delta_sharing_manifest(bundle, output_root / \"delta\")\n elif normalized == \"s3_manifest\":\n written[normalized] = write_s3_asset_manifest(bundle, output_root / \"s3_manifest\")\n else:\n raise ValueError(f\"Unsupported delivery shape: {shape}\")\n return {\"release_dir\": str(release), \"delivery_dir\": str(output_root), \"shapes\": written}","instruction":"Explain the role of `def write_delivery_shapes(release_dir: str | Path, shapes: list[str]) -> dict[str, Any]` in Primitive Foundry.","output":"`write_delivery_shapes` is a function in `primitive_foundry.delivery.__init__`. It belongs to the release area of Primitive Foundry.","source_id":"primitive_foundry.delivery.__init__.write_delivery_shapes","task":"python_symbol_explanation"} {"id":"primitive_foundry.delivery.__init__.verify_delivery_shapes::explain","input":"Module: primitive_foundry.delivery.__init__\nDomains: release\nSource path: primitive_foundry/delivery/__init__.py\n\ndef verify_delivery_shapes(release_dir: str | Path, shapes: list[str]) -> dict[str, Any]:\n release = Path(release_dir)\n failures = []\n for shape in shapes:\n normalized = shape.strip().lower()\n if not normalized:\n continue\n manifest = release / \"delivery\" / normalized / \"DELIVERY_MANIFEST.json\"\n if not manifest.exists():\n failures.append(f\"missing_delivery_manifest:{normalized}\")\n return {\"passed\": not failures, \"failures\": failures, \"release_dir\": str(release)}","instruction":"Explain the role of `def verify_delivery_shapes(release_dir: str | Path, shapes: list[str]) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_delivery_shapes` is a function in `primitive_foundry.delivery.__init__`. It belongs to the release area of Primitive Foundry.","source_id":"primitive_foundry.delivery.__init__.verify_delivery_shapes","task":"python_symbol_explanation"} {"id":"primitive_foundry.delivery.delta_sharing.write_delta_sharing_manifest::explain","input":"Module: primitive_foundry.delivery.delta_sharing\nDomains: dataset, atomic_write\nSource path: primitive_foundry/delivery/delta_sharing.py\n\ndef write_delta_sharing_manifest(bundle_dir: Path, output_dir: Path) -> dict[str, Any]:\n output_dir.mkdir(parents=True, exist_ok=True)\n schema = json.loads((bundle_dir / \"SCHEMA.json\").read_text(encoding=\"utf-8\"))\n manifest = {\n \"shape\": \"delta\",\n \"protocol\": \"delta-sharing-compatible-local-manifest\",\n \"share\": \"primitive_foundry\",\n \"schema\": \"aml\",\n \"table\": \"source_foundry_records\",\n \"source_bundle\": str(bundle_dir),\n \"dataset_family\": schema.get(\"dataset_family\"),\n \"dataset_version\": schema.get(\"dataset_version\"),\n \"required_fields\": schema.get(\"required_fields\", []),\n \"cloud_upload_performed\": False,\n }\n atomic_write_json(output_dir / \"DELIVERY_MANIFEST.json\", manifest)\n return manifest","instruction":"Explain the role of `def write_delta_sharing_manifest(bundle_dir: Path, output_dir: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`write_delta_sharing_manifest` is a function in `primitive_foundry.delivery.delta_sharing`. It belongs to the dataset, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.delivery.delta_sharing.write_delta_sharing_manifest","task":"python_symbol_explanation"} {"id":"primitive_foundry.delivery.parquet.write_parquet_bundle::explain","input":"Module: primitive_foundry.delivery.parquet\nDomains: atomic_write\nSource path: primitive_foundry/delivery/parquet.py\n\ndef write_parquet_bundle(jsonl_path: Path, output_dir: Path) -> dict[str, Any]:\n import pyarrow as pa\n import pyarrow.parquet as pq\n\n output_dir.mkdir(parents=True, exist_ok=True)\n records = read_jsonl(jsonl_path)\n flattened = [flatten_record(record) for record in records]\n table = pa.Table.from_pylist(flattened)\n parquet_path = output_dir / \"source_foundry_records.parquet\"\n pq.write_table(table, parquet_path)\n manifest = {\n \"shape\": \"parquet\",\n \"artifact\": str(parquet_path),\n \"source_jsonl\": str(jsonl_path),\n \"record_count\": len(records),\n \"sha256\": sha256_bytes(parquet_path.read_bytes()),\n }\n atomic_write_json(output_dir / \"DELIVERY_MANIFEST.json\", manifest)\n return manifest","instruction":"Explain the role of `def write_parquet_bundle(jsonl_path: Path, output_dir: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`write_parquet_bundle` is a function in `primitive_foundry.delivery.parquet`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.delivery.parquet.write_parquet_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.delivery.parquet.flatten_record::explain","input":"Module: primitive_foundry.delivery.parquet\nDomains: dataset\nSource path: primitive_foundry/delivery/parquet.py\n\ndef flatten_record(record: dict[str, Any]) -> dict[str, Any]:\n return {\n \"record_id\": record.get(\"record_id\"),\n \"dataset_family\": record.get(\"dataset_family\"),\n \"dataset_version\": record.get(\"dataset_version\"),\n \"event_type\": record.get(\"event_type\"),\n \"rubric_id\": record.get(\"rubric_id\"),\n \"product_family\": record.get(\"labels\", {}).get(\"product_family\"),\n \"provenance_hash\": record.get(\"provenance_hash\"),\n \"source_hashes_json\": json.dumps(record.get(\"source_hashes\", []), sort_keys=True),\n \"features_json\": json.dumps(record.get(\"features\", {}), sort_keys=True),\n \"labels_json\": json.dumps(record.get(\"labels\", {}), sort_keys=True),\n \"domain_review_json\": json.dumps(record.get(\"domain_review\", {}), sort_keys=True),\n \"family_fields_json\": json.dumps(record.get(\"family_fields\", {}), sort_keys=True),\n }","instruction":"Explain the role of `def flatten_record(record: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`flatten_record` is a function in `primitive_foundry.delivery.parquet`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.delivery.parquet.flatten_record","task":"python_symbol_explanation"} {"id":"primitive_foundry.delivery.tar_gz.write_tar_gz_bundle::explain","input":"Module: primitive_foundry.delivery.tar_gz\nDomains: atomic_write\nSource path: primitive_foundry/delivery/tar_gz.py\n\ndef write_tar_gz_bundle(bundle_dir: Path, output_dir: Path) -> dict[str, Any]:\n output_dir.mkdir(parents=True, exist_ok=True)\n archive_path = output_dir / \"bundle.tar.gz\"\n write_deterministic_tar_gz(archive_path, [(bundle_dir, \"bundle\")])\n manifest = {\n \"shape\": \"tar_gz\",\n \"artifact\": str(archive_path),\n \"sha256\": sha256_bytes(archive_path.read_bytes()),\n }\n atomic_write_json(output_dir / \"DELIVERY_MANIFEST.json\", manifest)\n return manifest","instruction":"Explain the role of `def write_tar_gz_bundle(bundle_dir: Path, output_dir: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`write_tar_gz_bundle` is a function in `primitive_foundry.delivery.tar_gz`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.delivery.tar_gz.write_tar_gz_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.exporters.croissant._file_objects::explain","input":"Module: primitive_foundry.exporters.croissant\nDomains: exporter\nSource path: primitive_foundry/exporters/croissant.py\n\ndef _file_objects(bundle_dir: Path) -> list[dict[str, Any]]:\n files: list[dict[str, Any]] = []\n for relative in (\n \"data/train.jsonl\",\n \"data/validation.jsonl\",\n \"data/test.jsonl\",\n \"sample/sample_500.jsonl\",\n ):\n target = bundle_dir / relative\n if not target.exists():\n continue\n digest = hashlib.sha256(target.read_bytes()).hexdigest()\n files.append(\n {\n \"@type\": \"cr:FileObject\",\n \"@id\": f\"file/{relative}\",\n \"name\": relative,\n \"contentUrl\": relative,\n \"encodingFormat\": \"application/x-ndjson\",\n \"sha256\": digest,\n }\n )\n return files","instruction":"Explain the role of `def _file_objects(bundle_dir: Path) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`_file_objects` is a function in `primitive_foundry.exporters.croissant`. It belongs to the exporter area of Primitive Foundry.","source_id":"primitive_foundry.exporters.croissant._file_objects","task":"python_symbol_explanation"} {"id":"primitive_foundry.exporters.croissant.build_croissant::explain","input":"Module: primitive_foundry.exporters.croissant\nDomains: release, commercial, license, dataset, exporter, compliance\nSource path: primitive_foundry/exporters/croissant.py\n\ndef build_croissant(release_dir: str | Path, listing: dict[str, Any]) -> dict[str, Any]:\n directory = Path(release_dir)\n bundle = directory / \"bundle\"\n\n license_field = str(listing.get(\"license\") or \"private-commercial-evaluation\")\n family = str(listing.get(\"family\") or \"primitive_foundry_release\")\n record_count = int(listing.get(\"record_count\") or 0)\n description = str(listing.get(\"description\") or \"\")\n title = str(listing.get(\"title\") or family)\n version = str(listing.get(\"version\") or \"1.0.0\")\n release_id = str(listing.get(\"release_id\") or family)\n\n croissant = {\n \"@context\": CROISSANT_CONTEXT,\n \"@type\": \"sc:Dataset\",\n \"@id\": release_id,\n \"conformsTo\": \"http://mlcommons.org/croissant/1.0\",\n \"name\": title,\n \"description\": description,\n \"version\": version,\n \"license\": license_field,\n \"url\": f\"local://primitive_foundry/{release_id}\",\n \"creator\": {\n \"@type\": \"sc:Organization\",\n \"name\": \"Primitive Origins LLC\",\n },\n \"datePublished\": listing.get(\"created_at\"),\n \"keywords\": [\n family,\n \"primitive_foundry\",\n *(listing.get(\"usage_rights\", [])),\n ],\n \"inLanguage\": \"en\",\n \"isLiveDataset\": False,\n \"distribution\": _file_objects(bundle),\n \"recordSet\": [\n {\n \"@type\": \"cr:RecordSet\",\n \"@id\": f\"records/{family}\",\n \"name\": family,\n \"description\": f\"Records for the {family} release\",\n \"field\": [\n {\n \"@type\": \"cr:Field\",\n \"@id\": \"field/record_id\",\n \"name\": \"record_id\",\n \"dataType\": \"sc:Text\",\n },\n {\n \"@type\": \"cr:Field\",\n \"@id\": \"field/rubric_id\",\n \"name\": \"rubric_id\",\n \"dataType\": \"sc:Text\",\n },\n ],\n }\n ],\n \"cr:metadata\": {\n \"record_count\": record_count,\n \"rubric_id\": listing.get(\"rubric_id\"),\n \"release_id\": release_id,\n \"patent_sensitive\": listing.get(\"compliance\", {}).get(\"patent_sensitive\", True),\n },\n }\n return croissant","instruction":"Explain the role of `def build_croissant(release_dir: str | Path, listing: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_croissant` is a function in `primitive_foundry.exporters.croissant`. It belongs to the release, commercial, license, dataset, exporter, compliance area of Primitive Foundry.","source_id":"primitive_foundry.exporters.croissant.build_croissant","task":"python_symbol_explanation"} {"id":"primitive_foundry.exporters.croissant.write_croissant::explain","input":"Module: primitive_foundry.exporters.croissant\nDomains: release, marketplace, exporter, atomic_write\nSource path: primitive_foundry/exporters/croissant.py\n\ndef write_croissant(release_dir: str | Path, listing: dict[str, Any]) -> Path:\n directory = Path(release_dir)\n payload = build_croissant(directory, listing)\n # Sibling artifact written at the release root, not inside bundle/.\n # bundle/ is sealed by MANIFEST.lock; writing into it post-seal would\n # invalidate the lock. Buyers find the file alongside MARKETPLACE_LISTING.\n target = directory / \"CROISSANT.jsonld\"\n locked_atomic_write_json(target, payload)\n return target","instruction":"Explain the role of `def write_croissant(release_dir: str | Path, listing: dict[str, Any]) -> Path` in Primitive Foundry.","output":"`write_croissant` is a function in `primitive_foundry.exporters.croissant`. It belongs to the release, marketplace, exporter, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.exporters.croissant.write_croissant","task":"python_symbol_explanation"} {"id":"primitive_foundry.exporters.datasheet.build_datasheet::explain","input":"Module: primitive_foundry.exporters.datasheet\nDomains: sterilization, release, marketplace, commercial, license, dataset, benchmark, exporter, compliance\nSource path: primitive_foundry/exporters/datasheet.py\n\ndef build_datasheet(listing: dict[str, Any]) -> str:\n family = _fmt(listing.get(\"family\"))\n title = _fmt(listing.get(\"title\"))\n description = _fmt(listing.get(\"description\"))\n release_id = _fmt(listing.get(\"release_id\"))\n version = _fmt(listing.get(\"version\"))\n license_field = _fmt(listing.get(\"license\"), \"private-commercial-evaluation\")\n record_count = listing.get(\"record_count\", \"Not specified\")\n market_regions = \", \".join(listing.get(\"market_regions\") or []) or \"Not specified\"\n\n return f\"\"\"# Datasheet for {title}\n\nRelease ID: `{release_id}` \u00b7 Version: `{version}` \u00b7 Family: `{family}`\n\n## Motivation\n\n**For what purpose was the dataset created?**\n{description}\n\n**Who created the dataset and on whose behalf?**\nPrimitive Origins LLC. Private-commercial release; no external grant\nfunding underwrites this artifact.\n\n**Who funded the creation of the dataset?**\nInternally funded.\n\n## Composition\n\n**What do the instances represent?**\nSterilized, derived records suitable for buyer-side evaluation of the\n{family} family. Raw private source files are not included.\n\n**How many instances are there in total?**\n{record_count}\n\n**Is any information missing from individual instances?**\nPersonally identifying information, raw source paths, secrets, and\nunder-13 (COPPA) signals are excluded by the sterilization pipeline.\n\n**Are there recommended data splits?**\nStandard `data/train.jsonl`, `data/validation.jsonl`, `data/test.jsonl`\nsplits when present. A 500-record sample is provided when applicable.\n\n## Collection Process\n\n**How was the data associated with each instance acquired?**\nRecords are derived from local private source events processed by the\nPrimitive Foundry. Each event is fingerprinted, deduplicated, and scored\nbefore promotion.\n\n**Were the individuals notified about the data collection?**\nNot applicable \u2014 instances are derived, non-personal benchmark records.\n\n## Preprocessing / Cleaning / Labeling\n\n**Was any preprocessing/cleaning/labeling of the data done?**\nYes. Sterilization redacts PII, secrets, paths, and identifying tokens.\nPromotion verifies provenance and quality gates. The bundle is sealed by\n`MANIFEST.lock`.\n\n## Uses\n\n**Has the dataset been used for any tasks already?**\nInternal benchmark evaluation; promotion and review gates pass before\nrelease.\n\n**What tasks should the dataset not be used for?**\nTraining of biometric, identity-resolution, or surveillance systems is\nout of scope. Use in regulated healthcare or financial AI deployment\nrequires the buyer's own compliance review (see `COMPLIANCE_MATRIX.json`).\n\n## Distribution\n\n**How is the dataset distributed?**\nAs a signed `.tar.gz` package containing the bundle, the listing,\nprovenance and quality artifacts, the FTC claims matrix, and the\ncompliance matrix.\n\n**Will the dataset be distributed under a copyright or other\nintellectual-property license?**\n{license_field}\n\n## Maintenance\n\n**Who is supporting/hosting/maintaining the dataset?**\nPrimitive Origins LLC.\n\n**How can the owner be contacted?**\nSee the support contact in `MARKETPLACE_METADATA.json` once the listing\nis approved for external distribution.\n\n**Will the dataset be updated?**\nNew data requires a new release version. Source retention policy is\ndocumented in `COMPLIANCE_MATRIX.json`.\n\n## Markets\n\nIntended commercial regions: {market_regions}.\n\"\"\"","instruction":"Explain the role of `def build_datasheet(listing: dict[str, Any]) -> str` in Primitive Foundry.","output":"`build_datasheet` is a function in `primitive_foundry.exporters.datasheet`. It belongs to the sterilization, release, marketplace, commercial, license, dataset, benchmark, exporter, compliance area of Primitive Foundry.","source_id":"primitive_foundry.exporters.datasheet.build_datasheet","task":"python_symbol_explanation"} {"id":"primitive_foundry.exporters.datasheet.write_datasheet::explain","input":"Module: primitive_foundry.exporters.datasheet\nDomains: release, exporter, atomic_write\nSource path: primitive_foundry/exporters/datasheet.py\n\ndef write_datasheet(release_dir: str | Path, listing: dict[str, Any]) -> Path:\n directory = Path(release_dir)\n target = directory / \"DATASHEET.md\"\n atomic_write_text(target, build_datasheet(listing))\n return target","instruction":"Explain the role of `def write_datasheet(release_dir: str | Path, listing: dict[str, Any]) -> Path` in Primitive Foundry.","output":"`write_datasheet` is a function in `primitive_foundry.exporters.datasheet`. It belongs to the release, exporter, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.exporters.datasheet.write_datasheet","task":"python_symbol_explanation"} {"id":"primitive_foundry.exporters.dcat.build_dcat::explain","input":"Module: primitive_foundry.exporters.dcat\nDomains: release, commercial, license, dataset, exporter\nSource path: primitive_foundry/exporters/dcat.py\n\ndef build_dcat(release_dir: str | Path, listing: dict[str, Any]) -> dict[str, Any]:\n release_id = str(listing.get(\"release_id\") or \"primitive_foundry_release\")\n family = str(listing.get(\"family\") or \"\")\n payload = {\n \"@context\": DCAT_CONTEXT,\n \"@type\": \"Dataset\",\n \"@id\": f\"local://primitive_foundry/{release_id}\",\n \"dct:title\": str(listing.get(\"title\") or release_id),\n \"dct:description\": str(listing.get(\"description\") or \"\"),\n \"dct:identifier\": release_id,\n \"dct:license\": str(listing.get(\"license\") or \"private-commercial-evaluation\"),\n \"dct:issued\": listing.get(\"created_at\"),\n \"dct:publisher\": {\"@type\": \"foaf:Organization\", \"foaf:name\": \"Primitive Origins LLC\"},\n \"keyword\": [family, \"primitive_foundry\"],\n \"version\": str(listing.get(\"version\") or \"1.0.0\"),\n \"distribution\": [\n {\n \"@type\": \"Distribution\",\n \"dct:title\": f\"{release_id}.{listing.get('delivery_format', 'tar.gz')}\",\n \"mediaType\": \"application/gzip\",\n \"accessRights\": \"private-commercial\",\n }\n ],\n }\n return payload","instruction":"Explain the role of `def build_dcat(release_dir: str | Path, listing: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_dcat` is a function in `primitive_foundry.exporters.dcat`. It belongs to the release, commercial, license, dataset, exporter area of Primitive Foundry.","source_id":"primitive_foundry.exporters.dcat.build_dcat","task":"python_symbol_explanation"} {"id":"primitive_foundry.exporters.dcat.write_dcat::explain","input":"Module: primitive_foundry.exporters.dcat\nDomains: release, exporter, atomic_write\nSource path: primitive_foundry/exporters/dcat.py\n\ndef write_dcat(release_dir: str | Path, listing: dict[str, Any]) -> Path:\n directory = Path(release_dir)\n payload = build_dcat(directory, listing)\n target = directory / \"DCAT.jsonld\"\n locked_atomic_write_json(target, payload)\n return target","instruction":"Explain the role of `def write_dcat(release_dir: str | Path, listing: dict[str, Any]) -> Path` in Primitive Foundry.","output":"`write_dcat` is a function in `primitive_foundry.exporters.dcat`. It belongs to the release, exporter, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.exporters.dcat.write_dcat","task":"python_symbol_explanation"} {"id":"primitive_foundry.exporters.schema_org_dataset.build_schema_org_dataset::explain","input":"Module: primitive_foundry.exporters.schema_org_dataset\nDomains: release, commercial, license, dataset, exporter\nSource path: primitive_foundry/exporters/schema_org_dataset.py\n\ndef build_schema_org_dataset(release_dir: str | Path, listing: dict[str, Any]) -> dict[str, Any]:\n directory = Path(release_dir)\n release_id = str(listing.get(\"release_id\") or \"primitive_foundry_release\")\n family = str(listing.get(\"family\") or \"\")\n record_count = int(listing.get(\"record_count\") or 0)\n\n payload = {\n \"@context\": \"https://schema.org/\",\n \"@type\": \"Dataset\",\n \"@id\": f\"local://primitive_foundry/{release_id}\",\n \"name\": str(listing.get(\"title\") or release_id),\n \"description\": str(listing.get(\"description\") or \"\"),\n \"identifier\": release_id,\n \"license\": str(listing.get(\"license\") or \"private-commercial-evaluation\"),\n \"version\": str(listing.get(\"version\") or \"1.0.0\"),\n \"datePublished\": listing.get(\"created_at\"),\n \"creator\": {\n \"@type\": \"Organization\",\n \"name\": \"Primitive Origins LLC\",\n },\n \"keywords\": [family, \"primitive_foundry\", *(listing.get(\"usage_rights\", []))],\n \"size\": {\n \"@type\": \"QuantitativeValue\",\n \"value\": record_count,\n \"unitText\": \"records\",\n },\n \"distribution\": [\n {\n \"@type\": \"DataDownload\",\n \"encodingFormat\": str(listing.get(\"delivery_format\") or \"tar.gz\"),\n \"contentSize\": str(record_count),\n \"name\": f\"{release_id}.{listing.get('delivery_format', 'tar.gz')}\",\n }\n ],\n \"isAccessibleForFree\": False,\n \"conditionsOfAccess\": \"private-commercial \u2014 buyer agreement required\",\n \"spatialCoverage\": [\n {\"@type\": \"Place\", \"name\": region}\n for region in (listing.get(\"market_regions\") or [])\n ],\n }\n return payload","instruction":"Explain the role of `def build_schema_org_dataset(release_dir: str | Path, listing: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_schema_org_dataset` is a function in `primitive_foundry.exporters.schema_org_dataset`. It belongs to the release, commercial, license, dataset, exporter area of Primitive Foundry.","source_id":"primitive_foundry.exporters.schema_org_dataset.build_schema_org_dataset","task":"python_symbol_explanation"} {"id":"primitive_foundry.exporters.schema_org_dataset.write_schema_org_dataset::explain","input":"Module: primitive_foundry.exporters.schema_org_dataset\nDomains: release, dataset, exporter, atomic_write\nSource path: primitive_foundry/exporters/schema_org_dataset.py\n\ndef write_schema_org_dataset(release_dir: str | Path, listing: dict[str, Any]) -> Path:\n directory = Path(release_dir)\n payload = build_schema_org_dataset(directory, listing)\n target = directory / \"SCHEMA_ORG_DATASET.jsonld\"\n locked_atomic_write_json(target, payload)\n return target","instruction":"Explain the role of `def write_schema_org_dataset(release_dir: str | Path, listing: dict[str, Any]) -> Path` in Primitive Foundry.","output":"`write_schema_org_dataset` is a function in `primitive_foundry.exporters.schema_org_dataset`. It belongs to the release, dataset, exporter, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.exporters.schema_org_dataset.write_schema_org_dataset","task":"python_symbol_explanation"} {"id":"primitive_foundry.external_listing.approve_external_listing::explain","input":"Module: primitive_foundry.external_listing\nDomains: release, marketplace, commercial, atomic_write\nSource path: primitive_foundry/external_listing.py\n\ndef approve_external_listing(\n *,\n release_dir: str | Path,\n reviewer: str,\n notes: str,\n support_contact: str,\n refund_policy: str,\n tax_vat_status: str,\n package_output_dir: str | Path | None = None,\n) -> dict[str, Any]:\n directory = Path(release_dir)\n if not reviewer.strip():\n raise ValueError(\"reviewer is required\")\n if not notes.strip():\n raise ValueError(\"notes are required\")\n for name, value in (\n (\"support_contact\", support_contact),\n (\"refund_policy\", refund_policy),\n (\"tax_vat_status\", tax_vat_status),\n ):\n if is_placeholder(value):\n raise ValueError(f\"{name} must be set before external listing\")\n\n commercial_before = verify_commercial_release(directory)\n if not commercial_before[\"passed\"]:\n raise ValueError(\"Cannot approve external listing before commercial release verifies.\")\n\n listing_path = directory / \"MARKETPLACE_LISTING.json\"\n marketplace_path = directory / \"MARKETPLACE_METADATA.json\"\n legal_path = directory / \"LEGAL_REVIEW_PACKET.json\"\n readiness_path = directory / \"COMMERCIAL_READINESS.json\"\n manifest_path = directory / \"AUTONOMOUS_RELEASE.json\"\n\n listing = read_json(listing_path)\n marketplace = read_json(marketplace_path)\n legal = read_json(legal_path)\n manifest = read_json(manifest_path)\n\n complementary_failures = verify_complementary_bundle(directory, listing)\n if complementary_failures:\n raise ValueError(\n \"Cannot approve external listing \u2014 complementary-bundle gate failed: \"\n + \", \".join(complementary_failures)\n )\n card_failures = verify_card_accuracy(directory, listing)\n if card_failures:\n raise ValueError(\n \"Cannot approve external listing \u2014 FTC claim-accuracy gate failed: \"\n + \", \".join(card_failures)\n )\n # The FTC claims matrix lives at the release root, not in bundle/.\n # bundle/ is sealed by MANIFEST.lock at the time of packaging; writing\n # into it post-seal would invalidate the lock.\n claims_matrix = build_ftc_claims_matrix(directory, listing)\n locked_atomic_write_json(directory / \"FTC_CLAIMS_MATRIX.json\", claims_matrix)\n package_dir = validated_package_output_dir(directory, package_output_dir, manifest)\n if listing.get(\"externally_listable\") is True or legal.get(\"legal_review\", {}).get(\"approved\") is True:\n raise ValueError(\"External listing is already approved; create a new release/version for changes.\")\n\n marketplace[\"support_contact\"] = support_contact.strip()\n marketplace[\"refund_policy\"] = refund_policy.strip()\n marketplace[\"tax_vat_status\"] = tax_vat_status.strip()\n marketplace[\"external_listing_ready\"] = True\n marketplace[\"metadata_hash\"] = sha256_json({**marketplace, \"metadata_hash\": \"\"})\n write_json(marketplace_path, marketplace)\n\n legal[\"legal_review\"] = {\n \"approved\": True,\n \"reviewer\": reviewer.strip(),\n \"reviewed_at\": datetime.now(timezone.utc).isoformat(),\n \"notes\": notes.strip(),\n }\n legal[\"external_sale_blocked_until_approved\"] = False\n legal[\"legal_packet_hash\"] = sha256_json({**legal, \"legal_packet_hash\": \"\"})\n write_json(legal_path, legal)\n\n listing[\"marketplace_metadata_hash\"] = sha256_json(marketplace)\n listing[\"legal_review_hash\"] = sha256_json(legal)\n listing[\"externally_listable\"] = True\n listing[\"external_listing_approved_at\"] = legal[\"legal_review\"][\"reviewed_at\"]\n listing[\"listing_hash\"] = sha256_json({**listing, \"listing_hash\": \"\"})\n write_json(listing_path, listing)\n write_marketplace_channel_plan(\n release_dir=directory,\n listing=listing,\n marketplace_metadata=marketplace,\n )\n\n readiness = read_json(readiness_path)\n readiness[\"external_listing_ready\"] = True\n readiness[\"external_listing_approved_at\"] = legal[\"legal_review\"][\"reviewed_at\"]\n readiness[\"readiness_hash\"] = sha256_json({**readiness, \"readiness_hash\": \"\"})\n write_json(readiness_path, readiness)\n\n package = package_product(candidate_dir=directory, output_dir=package_dir)\n package_verify = verify_package(package[\"manifest\"])\n commercial_after = verify_commercial_release(directory)\n\n manifest[\"commercial_verify\"] = commercial_after\n manifest[\"package\"] = package\n manifest[\"package_verify\"] = package_verify\n manifest[\"external_listing_approved_at\"] = legal[\"legal_review\"][\"reviewed_at\"]\n manifest[\"release_hash\"] = sha256_json({**manifest, \"release_hash\": \"\"})\n write_json(manifest_path, manifest)\n\n external_final = verify_external_listing_release(directory)\n manifest = read_json(manifest_path)\n manifest[\"external_listing_verify\"] = external_final\n manifest[\"release_hash\"] = sha256_json({**manifest, \"release_hash\": \"\"})\n write_json(manifest_path, manifest)\n external_final = verify_external_listing_release(directory)\n return {\n \"approved\": external_final[\"passed\"],\n \"release_dir\": str(directory),\n \"reviewer\": reviewer.strip(),\n \"commercial_verify\": commercial_after,\n \"package_verify\": package_verify,\n \"external_verify\": external_final,\n \"package\": package,\n \"manifest\": str(manifest_path),\n }","instruction":"Explain the role of `def approve_external_listing(*, release_dir: str | Path, reviewer: str, notes: str, support_contact: str, refund_policy: str, tax_vat_status: str, package_output_dir: str | Path | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`approve_external_listing` is a function in `primitive_foundry.external_listing`. It belongs to the release, marketplace, commercial, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.external_listing.approve_external_listing","task":"python_symbol_explanation"} {"id":"primitive_foundry.external_listing.refresh_release_package::explain","input":"Module: primitive_foundry.external_listing\nDomains: release, marketplace, commercial, planner\nSource path: primitive_foundry/external_listing.py\n\ndef refresh_release_package(\n *,\n release_dir: str | Path,\n package_output_dir: str | Path | None = None,\n) -> dict[str, Any]:\n directory = Path(release_dir)\n manifest_path = directory / \"AUTONOMOUS_RELEASE.json\"\n if not manifest_path.exists():\n raise ValueError(f\"Missing autonomous release manifest: {manifest_path}\")\n\n channel_plan_path = directory / \"MARKETPLACE_CHANNEL_PLAN.json\"\n listing_path = directory / \"MARKETPLACE_LISTING.json\"\n marketplace_path = directory / \"MARKETPLACE_METADATA.json\"\n legal_path = directory / \"LEGAL_REVIEW_PACKET.json\"\n if listing_path.exists() and marketplace_path.exists() and legal_path.exists():\n listing = read_json(listing_path)\n marketplace = read_json(marketplace_path)\n legal = read_json(legal_path)\n metadata_changed = False\n for key, value in (\n (\"primary_marketplace\", \"aws_data_exchange\"),\n (\"secondary_marketplaces\", [\"snowflake_marketplace\", \"databricks_marketplace\"]),\n (\"community_funnel\", \"huggingface_hub\"),\n ):\n if marketplace.get(key) != value:\n marketplace[key] = value\n metadata_changed = True\n if metadata_changed:\n marketplace[\"metadata_hash\"] = sha256_json({**marketplace, \"metadata_hash\": \"\"})\n write_json(marketplace_path, marketplace)\n review_items = legal.setdefault(\"required_review_items\", [])\n if \"marketplace_channel_obligations\" not in review_items:\n review_items.append(\"marketplace_channel_obligations\")\n legal[\"legal_packet_hash\"] = sha256_json({**legal, \"legal_packet_hash\": \"\"})\n write_json(legal_path, legal)\n if metadata_changed or \"marketplace_channel_obligations\" in review_items:\n listing[\"marketplace_metadata_hash\"] = sha256_json(marketplace)\n listing[\"legal_review_hash\"] = sha256_json(legal)\n listing[\"listing_hash\"] = sha256_json({**listing, \"listing_hash\": \"\"})\n write_json(listing_path, listing)\n if not channel_plan_path.exists() or metadata_changed:\n write_marketplace_channel_plan(\n release_dir=directory,\n listing=listing,\n marketplace_metadata=marketplace,\n )\n elif not channel_plan_path.exists() and listing_path.exists() and marketplace_path.exists():\n write_marketplace_channel_plan(\n release_dir=directory,\n listing=read_json(listing_path),\n marketplace_metadata=read_json(marketplace_path),\n )\n\n commercial_before = verify_commercial_release(directory)\n if not commercial_before[\"passed\"]:\n raise ValueError(\"Cannot refresh package before commercial release verifies.\")\n\n manifest = read_json(manifest_path)\n package_dir = validated_package_output_dir(directory, package_output_dir, manifest)\n package = package_product(candidate_dir=directory, output_dir=package_dir)\n package_verify = verify_package(package[\"manifest\"])\n commercial_after = verify_commercial_release(directory)\n\n manifest[\"commercial_verify\"] = commercial_after\n manifest[\"package\"] = package\n manifest[\"package_verify\"] = package_verify\n manifest[\"release_hash\"] = sha256_json({**manifest, \"release_hash\": \"\"})\n write_json(manifest_path, manifest)\n\n from .product_planner import verify_autonomous_release\n\n release_verify = verify_autonomous_release(manifest_path)\n listing = read_json(directory / \"MARKETPLACE_LISTING.json\")\n legal = read_json(directory / \"LEGAL_REVIEW_PACKET.json\")\n external_verify = None\n if listing.get(\"externally_listable\") is True or legal.get(\"legal_review\", {}).get(\"approved\") is True:\n external_verify = verify_external_listing_release(directory)\n manifest = read_json(manifest_path)\n manifest[\"external_listing_verify\"] = external_verify\n manifest[\"release_hash\"] = sha256_json({**manifest, \"release_hash\": \"\"})\n write_json(manifest_path, manifest)\n release_verify = verify_autonomous_release(manifest_path)\n external_verify = verify_external_listing_release(directory)\n\n return {\n \"refreshed\": release_verify[\"passed\"] and package_verify[\"passed\"] and (external_verify is None or external_verify[\"passed\"]),\n \"release_dir\": str(directory),\n \"package\": package,\n \"package_verify\": package_verify,\n \"commercial_verify\": commercial_after,\n \"release_verify\": release_verify,\n \"external_verify\": external_verify,\n \"manifest\": str(manifest_path),\n }","instruction":"Explain the role of `def refresh_release_package(*, release_dir: str | Path, package_output_dir: str | Path | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`refresh_release_package` is a function in `primitive_foundry.external_listing`. It belongs to the release, marketplace, commercial, planner area of Primitive Foundry.","source_id":"primitive_foundry.external_listing.refresh_release_package","task":"python_symbol_explanation"} {"id":"primitive_foundry.external_listing.repair_release_artifacts::explain","input":"Module: primitive_foundry.external_listing\nDomains: release, marketplace, commercial, planner\nSource path: primitive_foundry/external_listing.py\n\ndef repair_release_artifacts(\n *,\n release_dir: str | Path,\n package_output_dir: str | Path | None = None,\n) -> dict[str, Any]:\n directory = Path(release_dir)\n manifest_path = directory / \"AUTONOMOUS_RELEASE.json\"\n if not manifest_path.exists():\n raise ValueError(f\"Missing autonomous release manifest: {manifest_path}\")\n manifest = read_json(manifest_path)\n if manifest.get(\"manifest_type\") != \"aml_autonomous_product_release\":\n raise ValueError(\"Can only repair autonomous product releases.\")\n\n listing_path = directory / \"MARKETPLACE_LISTING.json\"\n legal_path = directory / \"LEGAL_REVIEW_PACKET.json\"\n if listing_path.exists():\n listing = read_json(listing_path)\n if listing.get(\"externally_listable\") is True:\n raise ValueError(\"Externally listed releases must be repaired with refresh-release-package.\")\n if legal_path.exists():\n legal = read_json(legal_path)\n if legal.get(\"legal_review\", {}).get(\"approved\") is True:\n raise ValueError(\"Legally approved releases must be repaired with refresh-release-package.\")\n\n release_id = str(manifest.get(\"release_id\") or directory.name)\n if release_id != directory.name:\n raise ValueError(\"Release manifest id does not match release directory.\")\n family = manifest.get(\"family\")\n target_size = manifest.get(\"target_size\")\n candidate = manifest.get(\"candidate\") or {}\n if not family or not target_size or not candidate:\n raise ValueError(\"Release manifest is missing family, target_size, or candidate payload.\")\n\n events_path = directory / \"events.jsonl\"\n event_count = count_jsonl_rows(events_path)\n record_count = int(manifest.get(\"record_count\") or event_count)\n source_diversity = int(manifest.get(\"source_diversity\") or max(1, event_count))\n commercial = write_commercial_artifacts(\n release_dir=directory,\n release_id=release_id,\n family=family,\n target_size=target_size,\n target_count=manifest.get(\"target_count\"),\n record_count=record_count,\n source_diversity=source_diversity,\n candidate=candidate,\n )\n commercial_verify = verify_commercial_release(directory)\n if not commercial_verify[\"passed\"]:\n raise ValueError(\"Commercial artifact repair did not verify.\")\n\n package_dir = Path(package_output_dir) if package_output_dir else directory.parent.parent / \"packages\"\n expected_package_dir = directory.parent.parent / \"packages\"\n if package_dir.resolve(strict=False) != expected_package_dir.resolve(strict=False):\n raise ValueError(f\"package_output_dir must be the release package root: {expected_package_dir}\")\n package = package_product(candidate_dir=directory, output_dir=package_dir)\n package_verify = verify_package(package[\"manifest\"])\n\n manifest[\"commercial\"] = commercial\n manifest[\"commercial_verify\"] = commercial_verify\n manifest[\"package\"] = package\n manifest[\"package_verify\"] = package_verify\n manifest[\"record_count\"] = record_count\n manifest[\"source_diversity\"] = source_diversity\n manifest[\"release_hash\"] = sha256_json({**manifest, \"release_hash\": \"\"})\n write_json(manifest_path, manifest)\n\n from .product_planner import verify_autonomous_release\n\n release_verify = verify_autonomous_release(manifest_path)\n return {\n \"repaired\": release_verify[\"passed\"],\n \"release_dir\": str(directory),\n \"commercial\": commercial,\n \"commercial_verify\": commercial_verify,\n \"package\": package,\n \"package_verify\": package_verify,\n \"release_verify\": release_verify,\n \"manifest\": str(manifest_path),\n }","instruction":"Explain the role of `def repair_release_artifacts(*, release_dir: str | Path, package_output_dir: str | Path | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`repair_release_artifacts` is a function in `primitive_foundry.external_listing`. It belongs to the release, marketplace, commercial, planner area of Primitive Foundry.","source_id":"primitive_foundry.external_listing.repair_release_artifacts","task":"python_symbol_explanation"} {"id":"primitive_foundry.external_listing.count_jsonl_rows::explain","input":"Module: primitive_foundry.external_listing\nDomains: foundry\nSource path: primitive_foundry/external_listing.py\n\ndef count_jsonl_rows(path: Path) -> int:\n if not path.exists():\n return 0\n count = 0\n with path.open(\"r\", encoding=\"utf-8\") as handle:\n for line in handle:\n if line.strip():\n count += 1\n return count","instruction":"Explain the role of `def count_jsonl_rows(path: Path) -> int` in Primitive Foundry.","output":"`count_jsonl_rows` is a function in `primitive_foundry.external_listing`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.external_listing.count_jsonl_rows","task":"python_symbol_explanation"} {"id":"primitive_foundry.external_listing.read_json::explain","input":"Module: primitive_foundry.external_listing\nDomains: foundry\nSource path: primitive_foundry/external_listing.py\n\ndef read_json(path: Path) -> dict[str, Any]:\n return json.loads(path.read_text(encoding=\"utf-8\"))","instruction":"Explain the role of `def read_json(path: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`read_json` is a function in `primitive_foundry.external_listing`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.external_listing.read_json","task":"python_symbol_explanation"} {"id":"primitive_foundry.external_listing.write_json::explain","input":"Module: primitive_foundry.external_listing\nDomains: foundry\nSource path: primitive_foundry/external_listing.py\n\ndef write_json(path: Path, payload: dict[str, Any]) -> None:\n path.write_text(json.dumps(payload, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")","instruction":"Explain the role of `def write_json(path: Path, payload: dict[str, Any]) -> None` in Primitive Foundry.","output":"`write_json` is a function in `primitive_foundry.external_listing`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.external_listing.write_json","task":"python_symbol_explanation"} {"id":"primitive_foundry.external_listing.validated_package_output_dir::explain","input":"Module: primitive_foundry.external_listing\nDomains: release\nSource path: primitive_foundry/external_listing.py\n\ndef validated_package_output_dir(\n release_dir: Path,\n requested_output_dir: str | Path | None,\n manifest: dict[str, Any],\n) -> Path:\n package_manifest = manifest.get(\"package\", {}).get(\"manifest\")\n if not package_manifest:\n raise ValueError(\"Release manifest is missing package manifest path.\")\n package_dir = Path(requested_output_dir) if requested_output_dir else Path(package_manifest).parent\n expected = release_dir.parent.parent / \"packages\"\n if package_dir.resolve(strict=False) != expected.resolve(strict=False):\n raise ValueError(f\"package_output_dir must be the release package root: {expected}\")\n return package_dir","instruction":"Explain the role of `def validated_package_output_dir(release_dir: Path, requested_output_dir: str | Path | None, manifest: dict[str, Any]) -> Path` in Primitive Foundry.","output":"`validated_package_output_dir` is a function in `primitive_foundry.external_listing`. It belongs to the release area of Primitive Foundry.","source_id":"primitive_foundry.external_listing.validated_package_output_dir","task":"python_symbol_explanation"} {"id":"primitive_foundry.external_listing.is_placeholder::explain","input":"Module: primitive_foundry.external_listing\nDomains: foundry\nSource path: primitive_foundry/external_listing.py\n\ndef is_placeholder(value: Any) -> bool:\n text = str(value or \"\").strip().lower()\n return not text or text.startswith(\"tbd\") or \"before-external-listing\" in text","instruction":"Explain the role of `def is_placeholder(value: Any) -> bool` in Primitive Foundry.","output":"`is_placeholder` is a function in `primitive_foundry.external_listing`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.external_listing.is_placeholder","task":"python_symbol_explanation"} {"id":"primitive_foundry.families.ProductFamily::explain","input":"Module: primitive_foundry.families\nDomains: planner\nSource path: primitive_foundry/families.py\n\nclass ProductFamily:\n name: str\n title: str\n category: str\n product_kind: str\n active: bool = True\n planner_enabled: bool = True\n legacy: bool = False\n aliases: tuple[str, ...] = field(default_factory=tuple)","instruction":"Explain the role of `class ProductFamily` in Primitive Foundry.","output":"`ProductFamily` is a class in `primitive_foundry.families`. It belongs to the planner area of Primitive Foundry.","source_id":"primitive_foundry.families.ProductFamily","task":"python_symbol_explanation"} {"id":"primitive_foundry.families.family_title::explain","input":"Module: primitive_foundry.families\nDomains: foundry\nSource path: primitive_foundry/families.py\n\ndef family_title(name: str) -> str:\n return FAMILY_TITLES.get(name, name.replace(\"_\", \" \").title())","instruction":"Explain the role of `def family_title(name: str) -> str` in Primitive Foundry.","output":"`family_title` is a function in `primitive_foundry.families`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.families.family_title","task":"python_symbol_explanation"} {"id":"primitive_foundry.families.marketplace_category::explain","input":"Module: primitive_foundry.families\nDomains: marketplace, dataset, benchmark\nSource path: primitive_foundry/families.py\n\ndef marketplace_category(name: str) -> str:\n family = REGISTRY.get(canonical_family(name))\n if family is None:\n return \"ai-evaluation-data-products\"\n if family.category == \"dataset\":\n return \"datasets\"\n if family.category == \"evaluation\":\n return \"evaluation-harnesses\"\n if family.category == \"benchmark\":\n return \"benchmarks\"\n return \"ai-evaluation-data-products\"","instruction":"Explain the role of `def marketplace_category(name: str) -> str` in Primitive Foundry.","output":"`marketplace_category` is a function in `primitive_foundry.families`. It belongs to the marketplace, dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.families.marketplace_category","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.default_domain_review::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef default_domain_review() -> dict[str, Any]:\n return {\n \"review_status\": \"founder_attested_v1\",\n \"reviewer_name\": \"local-owner\",\n \"reviewer_credentials\": \"Founder review; SME review pending customer-discovery LOI\",\n \"reviewed_at\": DEFAULT_DOMAIN_REVIEWED_AT,\n \"attestation\": \"Expected label and rubric reviewed for internal consistency; provenance hash is source binding only.\",\n }","instruction":"Explain the role of `def default_domain_review() -> dict[str, Any]` in Primitive Foundry.","output":"`default_domain_review` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.default_domain_review","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.default_buyer_task::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef default_buyer_task(record: FoundryRecord) -> dict[str, Any]:\n return {\n \"family\": record.metadata.get(\"source_family\", \"context_lifecycle\"),\n \"inputs\": [\"query\", \"expected_cell_ids\", \"provenance_manifest\"],\n \"expected_output\": \"route decision with provenance-backed pass/fail score\",\n }","instruction":"Explain the role of `def default_buyer_task(record: FoundryRecord) -> dict[str, Any]` in Primitive Foundry.","output":"`default_buyer_task` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.default_buyer_task","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.rubric_id_for_record::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef rubric_id_for_record(record: FoundryRecord) -> str:\n rubric = record.metadata.get(\"rubric\") or {}\n buyer_task = record.metadata.get(\"buyer_task\") or {}\n if isinstance(rubric, dict):\n for key in (\"rubric_id\", \"id\", \"type\"):\n if rubric.get(key):\n return str(rubric[key])\n if isinstance(buyer_task, dict) and buyer_task.get(\"rubric_id\"):\n return str(buyer_task[\"rubric_id\"])\n return \"route_and_provenance\"","instruction":"Explain the role of `def rubric_id_for_record(record: FoundryRecord) -> str` in Primitive Foundry.","output":"`rubric_id_for_record` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.rubric_id_for_record","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.harness_version_payload::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef harness_version_payload() -> dict[str, Any]:\n return {\n \"package\": \"primitive-harness\",\n \"version\": PRIMITIVE_HARNESS_VERSION,\n \"score_command\": \"primitive-harness score --bundle --agent --output buyer_report.json\",\n }","instruction":"Explain the role of `def harness_version_payload() -> dict[str, Any]` in Primitive Foundry.","output":"`harness_version_payload` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.harness_version_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.rubric_manifest::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef rubric_manifest(records: list[dict[str, Any]]) -> dict[str, Any]:\n rubrics: dict[str, dict[str, Any]] = {}\n for record in records:\n features = record.get(\"features\", {})\n rubric = dict(features.get(\"rubric\") or {})\n rubric_id = (\n record.get(\"rubric_id\")\n or rubric.get(\"rubric_id\")\n or rubric.get(\"id\")\n or rubric.get(\"type\")\n or \"route_and_provenance\"\n )\n rubrics.setdefault(str(rubric_id), rubric)\n return {\n \"schema\": \"primitive-rubric-manifest.v1\",\n \"default_seed\": 0,\n \"record_count\": len(records),\n \"rubrics\": rubrics,\n }","instruction":"Explain the role of `def rubric_manifest(records: list[dict[str, Any]]) -> dict[str, Any]` in Primitive Foundry.","output":"`rubric_manifest` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.rubric_manifest","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.domain_review_manifest::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef domain_review_manifest(records: list[dict[str, Any]]) -> dict[str, Any]:\n reviews = [record.get(\"domain_review\", {}) for record in records]\n return {\n \"schema\": \"primitive-domain-review-manifest.v1\",\n \"record_count\": len(records),\n \"review_statuses\": sorted({str(review.get(\"review_status\", \"unreviewed\")) for review in reviews}),\n \"reviewers\": sorted({str(review.get(\"reviewer_name\", \"\")) for review in reviews if review.get(\"reviewer_name\")}),\n \"credential_notes\": sorted(\n {str(review.get(\"reviewer_credentials\", \"\")) for review in reviews if review.get(\"reviewer_credentials\")}\n ),\n }","instruction":"Explain the role of `def domain_review_manifest(records: list[dict[str, Any]]) -> dict[str, Any]` in Primitive Foundry.","output":"`domain_review_manifest` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.domain_review_manifest","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.SterilizationReport::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: sterilization\nSource path: primitive_foundry/foundry_bridge.py\n\nclass SterilizationReport:\n status: str = \"clean\"\n removed_fields: list[str] = field(default_factory=list)\n redacted_fields: list[str] = field(default_factory=list)\n risk_flags: list[str] = field(default_factory=list)\n notes: list[str] = field(default_factory=list)","instruction":"Explain the role of `class SterilizationReport` in Primitive Foundry.","output":"`SterilizationReport` is a class in `primitive_foundry.foundry_bridge`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.SterilizationReport","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.FoundryCompatibleRecord::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: sterilization, dataset\nSource path: primitive_foundry/foundry_bridge.py\n\nclass FoundryCompatibleRecord:\n record_id: str\n dataset_family: str\n dataset_version: str\n created_at: float\n source_event_ids: list[str]\n source_hashes: list[str]\n source_system: str\n run_id: str | None\n task_id: str | None\n agent_id_hash: str | None\n node_id_hash: str | None\n model_tier: str | None\n event_type: str\n task_category: str | None\n context_summary_type: str | None\n action_type: str | None\n outcome_label: str | None\n quality_label: str | None\n trust_delta: float | None\n authority_delta: str | None\n latency_bucket: str | None\n cost_bucket: str | None\n relevance_score_bucket: str | None\n rag_references: list[str] = field(default_factory=list)\n features: dict[str, Any] = field(default_factory=dict)\n labels: dict[str, Any] = field(default_factory=dict)\n rubric_id: str = \"\"\n family_fields: dict[str, Any] = field(default_factory=dict)\n domain_review: dict[str, Any] = field(default_factory=dict)\n sterilization: SterilizationReport = field(default_factory=SterilizationReport)\n provenance_hash: str = \"\"\n\n def to_json(self) -> dict[str, Any]:\n return asdict(self)\n\n def with_hash(self) -> \"FoundryCompatibleRecord\":\n payload = self.to_json()\n payload[\"provenance_hash\"] = \"\"\n digest = sha256_json(payload)\n return FoundryCompatibleRecord(**{**payload, \"provenance_hash\": digest})","instruction":"Explain the role of `class FoundryCompatibleRecord` in Primitive Foundry.","output":"`FoundryCompatibleRecord` is a class in `primitive_foundry.foundry_bridge`. It belongs to the sterilization, dataset area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.FoundryCompatibleRecord","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.record_to_foundry::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: sterilization, release, license, dataset, benchmark\nSource path: primitive_foundry/foundry_bridge.py\n\ndef record_to_foundry(record: FoundryRecord) -> FoundryCompatibleRecord:\n sterile_summary = sterilize_text(str(record.metadata.get(\"source_summary\") or \"\"), max_chars=240)\n source_payload = {\n \"record_id\": record.record_id,\n \"task\": record.task,\n \"domain_path\": record.domain_path,\n \"expected_cell_ids\": record.expected_cell_ids,\n \"valid_from\": record.valid_from,\n \"valid_until\": record.valid_until,\n \"source_type\": record.source_type,\n \"license\": record.license,\n \"rubric_id\": record.rubric_id,\n \"domain_review\": record.domain_review,\n \"family_fields\": record.family_fields,\n \"metadata\": record.metadata,\n }\n source_hash = str(record.metadata.get(\"source_hash\") or sha256_json(source_payload))\n source_event_id = str(record.metadata.get(\"source_id\") or record.record_id)\n dataset_version = str(\n record.metadata.get(\n \"dataset_version\",\n SOURCE_BACKED_DATASET_VERSION if record.source_type == \"private-curated\" else DEFAULT_DATASET_VERSION,\n )\n )\n foundry_record = FoundryCompatibleRecord(\n record_id=f\"foundry-{record.record_id}\",\n dataset_family=DATASET_FAMILY,\n dataset_version=dataset_version,\n created_at=float(record.metadata.get(\"created_at\", 0.0) or 0.0),\n source_event_ids=[source_event_id],\n source_hashes=[source_hash],\n source_system=\"primitive-foundry\",\n run_id=str(record.metadata.get(\"run_id\")) if record.metadata.get(\"run_id\") else None,\n task_id=record.record_id,\n agent_id_hash=None,\n node_id_hash=None,\n model_tier=None,\n event_type=f\"aml.{record.task}\",\n task_category=\"context_lifecycle\",\n context_summary_type=\"cell_lifecycle\",\n action_type=action_type_for_task(record.task),\n outcome_label=\"expected_route_defined\",\n quality_label=\"source_backed_private\" if record.source_type == \"private-curated\" else \"synthetic_private\",\n trust_delta=None,\n authority_delta=None,\n latency_bucket=None,\n cost_bucket=None,\n relevance_score_bucket=None,\n rag_references=[],\n features={\n \"domain_path\": record.domain_path,\n \"expected_cell_id\": record.expected_cell_id,\n \"expected_cell_ids\": record.expected_cell_ids,\n \"stale_cell_id\": record.stale_cell_id,\n \"replacement_for\": record.replacement_for,\n \"valid_from\": record.valid_from,\n \"valid_until\": record.valid_until,\n \"source_id\": record.metadata.get(\"source_id\"),\n \"source_summary\": sterile_summary.text,\n \"source_file_hash\": record.metadata.get(\"source_file_hash\"),\n \"raw_source_included\": record.metadata.get(\"raw_source_included\", False),\n \"rubric\": record.metadata.get(\"rubric\") or default_rubric(record),\n \"buyer_task\": record.metadata.get(\"buyer_task\") or default_buyer_task(record),\n \"product_family\": record.metadata.get(\"source_family\"),\n \"family_metadata\": record.family_fields or record.metadata.get(\"family_metadata\", {}),\n },\n labels={\n \"release_candidate\": True,\n \"sterilized\": True,\n \"event_family\": \"aml\",\n \"task\": record.task,\n \"source_type\": record.source_type,\n \"license\": record.license,\n \"product_family\": record.metadata.get(\"source_family\"),\n },\n rubric_id=record.rubric_id or rubric_id_for_record(record),\n family_fields=dict(record.family_fields or record.metadata.get(\"family_metadata\") or {}),\n domain_review=dict(record.domain_review or record.metadata.get(\"domain_review\") or default_domain_review()),\n sterilization=SterilizationReport(\n status=\"clean\",\n redacted_fields=sterile_summary.redacted_fields,\n risk_flags=sterile_summary.risk_flags,\n notes=[\"Foundry export contains derived benchmark labels, not raw private trace content.\"],\n ),\n )\n return foundry_record.with_hash()","instruction":"Explain the role of `def record_to_foundry(record: FoundryRecord) -> FoundryCompatibleRecord` in Primitive Foundry.","output":"`record_to_foundry` is a function in `primitive_foundry.foundry_bridge`. It belongs to the sterilization, release, license, dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.record_to_foundry","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.action_type_for_task::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef action_type_for_task(task: str) -> str:\n if task in {\"replace_cell_without_global_retrain\", \"apoptosis_event_replay\"}:\n return \"replace\"\n if task in {\"detect_stale_cell\", \"resolve_old_new_conflict\"}:\n return \"evaluate\"\n if task == \"multi_cell_routing\":\n return \"route_multi\"\n return \"route\"","instruction":"Explain the role of `def action_type_for_task(task: str) -> str` in Primitive Foundry.","output":"`action_type_for_task` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.action_type_for_task","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.export_foundry_records::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: dataset, atomic_write\nSource path: primitive_foundry/foundry_bridge.py\n\ndef export_foundry_records(dataset_path: str | Path, output_path: str | Path) -> dict[str, Any]:\n records = [record_to_foundry(record) for record in load_jsonl(dataset_path)]\n output = Path(output_path)\n output.parent.mkdir(parents=True, exist_ok=True)\n atomic_write_jsonl(output, [record.to_json() for record in records])\n quality = verify_foundry_records(output)\n return {\n \"dataset\": str(dataset_path),\n \"output\": str(output),\n \"record_count\": len(records),\n \"quality\": quality,\n }","instruction":"Explain the role of `def export_foundry_records(dataset_path: str | Path, output_path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`export_foundry_records` is a function in `primitive_foundry.foundry_bridge`. It belongs to the dataset, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.export_foundry_records","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.normalize_foundry_record::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef normalize_foundry_record(record: dict[str, Any]) -> dict[str, Any]:\n normalized = dict(record)\n features = dict(normalized.get(\"features\") or {})\n labels = dict(normalized.get(\"labels\") or {})\n expected_cell_ids = list(features.get(\"expected_cell_ids\") or [])\n if not expected_cell_ids and features.get(\"expected_cell_id\"):\n expected_cell_ids = [str(features[\"expected_cell_id\"])]\n features[\"expected_cell_ids\"] = expected_cell_ids\n if not features.get(\"rubric\"):\n features[\"rubric\"] = {\n \"type\": \"route_and_provenance\",\n \"pass_conditions\": [\"expected_cell_selected\", \"answer_contains_provenance\"],\n \"expected_cell_ids\": expected_cell_ids,\n }\n if not features.get(\"buyer_task\"):\n features[\"buyer_task\"] = {\n \"family\": features.get(\"product_family\") or labels.get(\"product_family\") or \"context_lifecycle\",\n \"inputs\": [\"query\", \"expected_cell_ids\", \"provenance_manifest\"],\n \"expected_output\": \"route decision with provenance-backed pass/fail score\",\n }\n if not features.get(\"product_family\"):\n features[\"product_family\"] = labels.get(\"product_family\") or features[\"buyer_task\"].get(\"family\")\n labels.setdefault(\"product_family\", features.get(\"product_family\"))\n normalized[\"features\"] = features\n normalized[\"labels\"] = labels\n if not normalized.get(\"domain_review\"):\n normalized[\"domain_review\"] = default_domain_review()\n if not normalized.get(\"rubric_id\"):\n normalized[\"rubric_id\"] = str(\n features.get(\"rubric\", {}).get(\"rubric_id\")\n or features.get(\"rubric\", {}).get(\"id\")\n or features.get(\"buyer_task\", {}).get(\"rubric_id\")\n or features.get(\"rubric\", {}).get(\"type\", \"route_and_provenance\")\n )\n if not normalized.get(\"family_fields\"):\n normalized[\"family_fields\"] = dict(features.get(\"family_metadata\") or {})\n normalized[\"provenance_hash\"] = \"\"\n normalized[\"provenance_hash\"] = provenance_hash_for_payload(normalized)\n return normalized","instruction":"Explain the role of `def normalize_foundry_record(record: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`normalize_foundry_record` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.normalize_foundry_record","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.build_foundry_bundle::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: sterilization, dataset\nSource path: primitive_foundry/foundry_bridge.py\n\ndef build_foundry_bundle(\n foundry_jsonl_path: str | Path,\n bundle_dir: str | Path,\n *,\n dataset_name: str = \"aml_context_lifecycle\",\n) -> dict[str, Any]:\n source = Path(foundry_jsonl_path)\n records = read_foundry_jsonl(source)\n quality = verify_foundry_records(source)\n target = Path(bundle_dir)\n data_dir = target / \"data\"\n sample_dir = target / \"sample\"\n data_dir.mkdir(parents=True, exist_ok=True)\n sample_dir.mkdir(parents=True, exist_ok=True)\n\n train, validation, test = split_records(records)\n write_jsonl_rows(train, data_dir / \"train.jsonl\")\n write_jsonl_rows(validation, data_dir / \"validation.jsonl\")\n write_jsonl_rows(test, data_dir / \"test.jsonl\")\n write_jsonl_rows(records[: min(500, len(records))], sample_dir / \"sample_500.jsonl\")\n shutil.copyfile(source, target / \"source_foundry_records.jsonl\")\n write_eval_harness(target)\n write_example_agents(target)\n\n schema = {\n \"format\": \"foundry-compatible-jsonl\",\n \"dataset_family\": DATASET_FAMILY,\n \"dataset_version\": dataset_version_for_bundle(records),\n \"record_count\": len(records),\n \"required_fields\": [\n \"record_id\",\n \"dataset_family\",\n \"dataset_version\",\n \"source_event_ids\",\n \"source_hashes\",\n \"source_system\",\n \"event_type\",\n \"sterilization\",\n \"domain_review\",\n \"rubric_id\",\n \"family_fields\",\n \"provenance_hash\",\n ],\n \"included_harness\": \"eval_harness/buyer_harness.py\",\n \"primitive_harness\": harness_version_payload(),\n }\n provenance = {\n \"dataset_name\": dataset_name,\n \"source_file\": \"source_foundry_records.jsonl\",\n \"record_count\": len(records),\n \"source_hashes\": sorted({item for record in records for item in record.get(\"source_hashes\", [])}),\n \"domain_review_statuses\": sorted(\n {\n str(record.get(\"domain_review\", {}).get(\"review_status\", \"unreviewed\"))\n for record in records\n }\n ),\n \"bundle_hash\": sha256_json({\"records\": records}),\n }\n checksums = write_bundle_files(target, schema, provenance, quality, records)\n return {\n \"bundle_dir\": str(target),\n \"record_count\": len(records),\n \"quality\": quality,\n \"checksums\": checksums,\n }","instruction":"Explain the role of `def build_foundry_bundle(foundry_jsonl_path: str | Path, bundle_dir: str | Path, *, dataset_name: str='aml_context_lifecycle') -> dict[str, Any]` in Primitive Foundry.","output":"`build_foundry_bundle` is a function in `primitive_foundry.foundry_bridge`. It belongs to the sterilization, dataset area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.build_foundry_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.repair_foundry_bundle::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: sterilization, dataset\nSource path: primitive_foundry/foundry_bridge.py\n\ndef repair_foundry_bundle(bundle_dir: str | Path) -> dict[str, Any]:\n target = Path(bundle_dir)\n source = target / \"source_foundry_records.jsonl\"\n if not source.exists():\n raise FileNotFoundError(f\"Bundle source_foundry_records.jsonl missing: {source}\")\n records = [normalize_foundry_record(record) for record in read_foundry_jsonl(source)]\n data_dir = target / \"data\"\n sample_dir = target / \"sample\"\n data_dir.mkdir(parents=True, exist_ok=True)\n sample_dir.mkdir(parents=True, exist_ok=True)\n\n write_jsonl_rows(records, source)\n train, validation, test = split_records(records)\n write_jsonl_rows(train, data_dir / \"train.jsonl\")\n write_jsonl_rows(validation, data_dir / \"validation.jsonl\")\n write_jsonl_rows(test, data_dir / \"test.jsonl\")\n write_jsonl_rows(records[: min(500, len(records))], sample_dir / \"sample_500.jsonl\")\n write_eval_harness(target)\n write_example_agents(target)\n\n quality = verify_foundry_records(source)\n schema = {\n \"format\": \"foundry-compatible-jsonl\",\n \"dataset_family\": DATASET_FAMILY,\n \"dataset_version\": dataset_version_for_bundle(records),\n \"record_count\": len(records),\n \"required_fields\": [\n \"record_id\",\n \"dataset_family\",\n \"dataset_version\",\n \"source_event_ids\",\n \"source_hashes\",\n \"source_system\",\n \"event_type\",\n \"sterilization\",\n \"domain_review\",\n \"rubric_id\",\n \"family_fields\",\n \"provenance_hash\",\n ],\n \"included_harness\": \"eval_harness/buyer_harness.py\",\n \"primitive_harness\": harness_version_payload(),\n }\n provenance = {\n \"dataset_name\": target.name,\n \"source_file\": \"source_foundry_records.jsonl\",\n \"record_count\": len(records),\n \"source_hashes\": sorted({item for record in records for item in record.get(\"source_hashes\", [])}),\n \"domain_review_statuses\": sorted(\n {str(record.get(\"domain_review\", {}).get(\"review_status\", \"unreviewed\")) for record in records}\n ),\n \"bundle_hash\": sha256_json({\"records\": records}),\n \"repair_status\": \"repaired_with_harness_and_domain_review\",\n }\n checksums = write_bundle_files(target, schema, provenance, quality, records)\n verify = verify_foundry_bundle(target)\n return {\n \"bundle_dir\": str(target),\n \"record_count\": len(records),\n \"quality\": quality,\n \"checksums\": checksums,\n \"verify\": verify,\n \"repaired\": verify[\"passed\"],\n }","instruction":"Explain the role of `def repair_foundry_bundle(bundle_dir: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`repair_foundry_bundle` is a function in `primitive_foundry.foundry_bridge`. It belongs to the sterilization, dataset area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.repair_foundry_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.verify_foundry_bundle::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: sterilization, license, dataset\nSource path: primitive_foundry/foundry_bridge.py\n\ndef verify_foundry_bundle(bundle_dir: str | Path) -> dict[str, Any]:\n bundle = Path(bundle_dir)\n required_files = [\n \"README.md\",\n \"DATASET_CARD.md\",\n \"LICENSE.md\",\n \"SCHEMA.json\",\n \"DATA_DICTIONARY.md\",\n \"QUALITY_REPORT.md\",\n \"PROVENANCE_MANIFEST.json\",\n \"BUYER_MANIFEST.json\",\n \"HARNESS_VERSION.json\",\n \"RUBRIC.json\",\n \"DOMAIN_REVIEW.json\",\n \"CHECKSUMS.sha256\",\n \"eval_harness/README.md\",\n \"eval_harness/buyer_harness.py\",\n \"examples/README.md\",\n \"examples/agent_always_fail.py\",\n \"examples/agent_partial.py\",\n \"examples/agent_perfect.py\",\n \"sample/sample_500.jsonl\",\n \"data/train.jsonl\",\n \"data/validation.jsonl\",\n \"data/test.jsonl\",\n \"source_foundry_records.jsonl\",\n ]\n failures = []\n for relative in required_files:\n if not (bundle / relative).exists():\n failures.append(f\"missing:{relative}\")\n\n if failures:\n return {\"passed\": False, \"bundle_dir\": str(bundle), \"failures\": failures}\n\n checksum_failures = verify_checksums(bundle)\n failures.extend(checksum_failures)\n\n source_records = read_foundry_jsonl(bundle / \"source_foundry_records.jsonl\")\n train = read_foundry_jsonl(bundle / \"data/train.jsonl\")\n validation = read_foundry_jsonl(bundle / \"data/validation.jsonl\")\n test = read_foundry_jsonl(bundle / \"data/test.jsonl\")\n sample = read_foundry_jsonl(bundle / \"sample/sample_500.jsonl\")\n schema = json.loads((bundle / \"SCHEMA.json\").read_text(encoding=\"utf-8\"))\n provenance = json.loads((bundle / \"PROVENANCE_MANIFEST.json\").read_text(encoding=\"utf-8\"))\n quality = verify_foundry_records(bundle / \"source_foundry_records.jsonl\")\n sterilization = verify_sterilized_bundle(bundle)\n harness = verify_eval_harness(bundle)\n harness_version = json.loads((bundle / \"HARNESS_VERSION.json\").read_text(encoding=\"utf-8\"))\n rubric = json.loads((bundle / \"RUBRIC.json\").read_text(encoding=\"utf-8\"))\n domain_review = json.loads((bundle / \"DOMAIN_REVIEW.json\").read_text(encoding=\"utf-8\"))\n\n split_count = len(train) + len(validation) + len(test)\n if split_count != len(source_records):\n failures.append(f\"split_count_mismatch:{split_count}!={len(source_records)}\")\n if schema.get(\"record_count\") != len(source_records):\n failures.append(\"schema_record_count_mismatch\")\n if provenance.get(\"record_count\") != len(source_records):\n failures.append(\"provenance_record_count_mismatch\")\n if len(sample) != min(500, len(source_records)):\n failures.append(\"sample_count_mismatch\")\n if not quality[\"passed\"]:\n failures.append(\"source_records_quality_failed\")\n if not sterilization[\"passed\"]:\n failures.append(\"bundle_sterilization_failed\")\n if not harness[\"passed\"]:\n failures.extend(f\"eval_harness:{item}\" for item in harness[\"failures\"])\n if harness_version.get(\"package\") != \"primitive-harness\" or not harness_version.get(\"version\"):\n failures.append(\"invalid_harness_version\")\n if rubric.get(\"record_count\") != len(source_records) or not rubric.get(\"rubrics\"):\n failures.append(\"invalid_rubric_manifest\")\n if domain_review.get(\"record_count\") != len(source_records) or not domain_review.get(\"review_statuses\"):\n failures.append(\"invalid_domain_review_manifest\")\n\n return {\n \"passed\": not failures,\n \"bundle_dir\": str(bundle),\n \"record_count\": len(source_records),\n \"split_count\": split_count,\n \"sample_count\": len(sample),\n \"failures\": failures,\n \"quality\": quality,\n \"sterilization\": sterilization,\n \"eval_harness\": harness,\n \"harness_version\": harness_version,\n }","instruction":"Explain the role of `def verify_foundry_bundle(bundle_dir: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_foundry_bundle` is a function in `primitive_foundry.foundry_bridge`. It belongs to the sterilization, license, dataset area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.verify_foundry_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.verify_checksums::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef verify_checksums(bundle: Path) -> list[str]:\n checksum_path = bundle / \"CHECKSUMS.sha256\"\n expected = {}\n with checksum_path.open(\"r\", encoding=\"utf-8\") as handle:\n for line_number, line in enumerate(handle, start=1):\n stripped = line.strip()\n if not stripped:\n continue\n parts = stripped.split(\" \", 1)\n if len(parts) != 2:\n return [f\"invalid_checksum_line:{line_number}\"]\n digest, relative = parts\n expected[relative] = digest\n\n failures = []\n for relative, digest in expected.items():\n path = bundle / relative\n if not path.exists():\n failures.append(f\"checksum_missing_file:{relative}\")\n continue\n actual = sha256_bytes(path.read_bytes())\n if actual != digest:\n failures.append(f\"checksum_mismatch:{relative}\")\n actual_files = {\n str(path.relative_to(bundle))\n for path in bundle.rglob(\"*\")\n if path.is_file() and path.name != \"CHECKSUMS.sha256\"\n }\n missing_from_manifest = sorted(actual_files - set(expected))\n if missing_from_manifest:\n failures.append(\"checksum_manifest_missing:\" + \",\".join(missing_from_manifest))\n return failures","instruction":"Explain the role of `def verify_checksums(bundle: Path) -> list[str]` in Primitive Foundry.","output":"`verify_checksums` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.verify_checksums","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.write_eval_harness::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef write_eval_harness(bundle: Path) -> None:\n harness_dir = bundle / \"eval_harness\"\n harness_dir.mkdir(parents=True, exist_ok=True)\n (harness_dir / \"README.md\").write_text(\n \"# Buyer Eval Harness\\n\\n\"\n \"Run `python eval_harness/buyer_harness.py --bundle . --report scored_report.json` \"\n \"from a bundle root, or import `BuyerHarness` and call `score(agent_callable)`.\\n\",\n encoding=\"utf-8\",\n )","instruction":"Explain the role of `def write_eval_harness(bundle: Path) -> None` in Primitive Foundry.","output":"`write_eval_harness` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.write_eval_harness","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.write_example_agents::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: benchmark, atomic_write\nSource path: primitive_foundry/foundry_bridge.py\n\ndef write_example_agents(bundle: Path) -> None:\n examples = bundle / \"examples\"\n harness_dir = bundle / \"eval_harness\"\n harness_dir.mkdir(parents=True, exist_ok=True)\n examples.mkdir(parents=True, exist_ok=True)\n atomic_write_text(\n examples / \"README.md\",\n \"# Example Agents\\n\\n\"\n \"Run with `primitive-harness score --bundle . --agent examples.agent_perfect:run --output report.json`.\\n\",\n )\n atomic_write_text(\n examples / \"agent_always_fail.py\",\n \"def run(record):\\n return {'answer': 'I do not know'}\\n\",\n )\n atomic_write_text(\n examples / \"agent_partial.py\",\n \"def run(record):\\n\"\n \" ids = record.get('features', {}).get('expected_cell_ids', [])\\n\"\n \" return {'selected_cell_ids': ids if str(record.get('record_id', '')).endswith(('0', '2', '4', '6', '8')) else []}\\n\",\n )\n atomic_write_text(\n examples / \"agent_perfect.py\",\n \"def run(record):\\n\"\n \" features = record.get('features', {})\\n\"\n \" return {'selected_cell_ids': features.get('expected_cell_ids', []), 'rubric_signals': features.get('rubric', {}).get('pass_conditions', [])}\\n\",\n )\n (harness_dir / \"buyer_harness.py\").write_text(\n '''from __future__ import annotations\n\nimport argparse\nimport json\nfrom pathlib import Path\nfrom typing import Any, Callable\n\n\nAgentCallable = Callable[[dict[str, Any]], dict[str, Any] | str]\n\n\ndef _read_jsonl(path: Path) -> list[dict[str, Any]]:\n rows: list[dict[str, Any]] = []\n with path.open(\"r\", encoding=\"utf-8\") as handle:\n for line in handle:\n stripped = line.strip()\n if stripped:\n rows.append(json.loads(stripped))\n return rows\n\n\nclass BuyerHarness:\n def __init__(self, bundle_dir: str | Path) -> None:\n self.bundle_dir = Path(bundle_dir)\n source = self.bundle_dir / \"source_foundry_records.jsonl\"\n if not source.exists():\n source = self.bundle_dir / \"data\" / \"test.jsonl\"\n self.records = _read_jsonl(source)\n\n def score(self, agent_callable: AgentCallable) -> dict[str, Any]:\n results = [self._score_record(record, agent_callable(record)) for record in self.records]\n passed = sum(1 for row in results if row[\"passed\"])\n return {\n \"benchmark\": \"Context Primitive Foundry Buyer Harness\",\n \"record_count\": len(results),\n \"pass_rate\": passed / len(results) if results else 0.0,\n \"results\": results,\n }\n\n def _score_record(self, record: dict[str, Any], answer: dict[str, Any] | str) -> dict[str, Any]:\n answer_text = json.dumps(answer, sort_keys=True) if isinstance(answer, dict) else str(answer)\n features = record.get(\"features\", {})\n expected = [str(item) for item in features.get(\"expected_cell_ids\", [])]\n rubric = features.get(\"rubric\", {})\n rubric_terms = [str(item) for item in rubric.get(\"pass_conditions\", [])]\n expected_hit = any(item in answer_text for item in expected)\n rubric_hit = not rubric_terms or any(item in answer_text for item in rubric_terms)\n return {\n \"record_id\": record.get(\"record_id\"),\n \"product_family\": features.get(\"product_family\"),\n \"task\": record.get(\"labels\", {}).get(\"task\"),\n \"passed\": bool(expected_hit and rubric_hit),\n \"scores\": {\n \"expected_label\": 1.0 if expected_hit else 0.0,\n \"rubric_signal\": 1.0 if rubric_hit else 0.0,\n },\n \"expected_cell_ids\": expected,\n }\n\n\ndef reference_agent(record: dict[str, Any]) -> dict[str, Any]:\n features = record.get(\"features\", {})\n rubric = features.get(\"rubric\", {})\n return {\n \"selected_cell_ids\": features.get(\"expected_cell_ids\", []),\n \"rationale\": \"reference answer for local harness smoke test\",\n \"rubric_signals\": rubric.get(\"pass_conditions\", []),\n }\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--bundle\", default=\".\")\n parser.add_argument(\"--report\")\n args = parser.parse_args()\n report = BuyerHarness(args.bundle).score(reference_agent)\n text = json.dumps(report, indent=2, sort_keys=True) + \"\\\\n\"\n if args.report:\n Path(args.report).write_text(text, encoding=\"utf-8\")\n else:\n print(text, end=\"\")\n\n\nif __name__ == \"__main__\":\n main()\n''',\n encoding=\"utf-8\",\n )","instruction":"Explain the role of `def write_example_agents(bundle: Path) -> None` in Primitive Foundry.","output":"`write_example_agents` is a function in `primitive_foundry.foundry_bridge`. It belongs to the benchmark, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.write_example_agents","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.verify_eval_harness::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef verify_eval_harness(bundle: Path) -> dict[str, Any]:\n harness = bundle / \"eval_harness\" / \"buyer_harness.py\"\n failures: list[str] = []\n if not harness.exists():\n return {\"passed\": False, \"failures\": [\"missing_buyer_harness\"]}\n try:\n compile(harness.read_text(encoding=\"utf-8\"), str(harness), \"exec\")\n except SyntaxError as exc:\n failures.append(f\"syntax_error:{exc.lineno}\")\n buyer_manifest = json.loads((bundle / \"BUYER_MANIFEST.json\").read_text(encoding=\"utf-8\"))\n if buyer_manifest.get(\"eval_harness\") != \"eval_harness/buyer_harness.py\":\n failures.append(\"buyer_manifest_missing_harness\")\n schema = json.loads((bundle / \"SCHEMA.json\").read_text(encoding=\"utf-8\"))\n if schema.get(\"included_harness\") != \"eval_harness/buyer_harness.py\":\n failures.append(\"schema_missing_harness\")\n if schema.get(\"primitive_harness\", {}).get(\"version\") != PRIMITIVE_HARNESS_VERSION:\n failures.append(\"schema_missing_primitive_harness_version\")\n harness_version = json.loads((bundle / \"HARNESS_VERSION.json\").read_text(encoding=\"utf-8\"))\n if harness_version.get(\"version\") != PRIMITIVE_HARNESS_VERSION:\n failures.append(\"harness_version_mismatch\")\n if buyer_manifest.get(\"primitive_harness_version\") != PRIMITIVE_HARNESS_VERSION:\n failures.append(\"buyer_manifest_missing_primitive_harness_version\")\n return {\"passed\": not failures, \"failures\": failures, \"harness\": str(harness)}","instruction":"Explain the role of `def verify_eval_harness(bundle: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_eval_harness` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.verify_eval_harness","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.write_bundle_files::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: license, dataset\nSource path: primitive_foundry/foundry_bridge.py\n\ndef write_bundle_files(\n target: Path,\n schema: dict[str, Any],\n provenance: dict[str, Any],\n quality: dict[str, Any],\n records: list[dict[str, Any]],\n) -> dict[str, str]:\n files = {\n \"README.md\": \"# Primitive Foundry Context Lifecycle Bundle\\n\\nPrivate Foundry-compatible export bundle.\\n\",\n \"DATASET_CARD.md\": \"# Dataset Card\\n\\nSynthetic private Foundry context lifecycle records.\\n\",\n \"LICENSE.md\": \"# Private License\\n\\nNo redistribution without explicit approval.\\n\",\n \"DATA_DICTIONARY.md\": \"# Data Dictionary\\n\\nRecords follow the Foundry-compatible sale-grade envelope.\\n\",\n \"QUALITY_REPORT.md\": \"# Quality Report\\n\\n```json\\n\"\n + json.dumps(\n {\n **quality,\n \"verified_by\": {\n \"review_status\": \"founder_attested_v1\",\n \"review_scope\": \"expected labels, rubrics, harness smoke test, and source-binding checks\",\n \"sme_review\": \"pending customer-discovery LOI\",\n },\n },\n indent=2,\n sort_keys=True,\n )\n + \"\\n```\\n\",\n }\n for name, content in files.items():\n (target / name).write_text(content, encoding=\"utf-8\")\n write_json(target / \"SCHEMA.json\", schema)\n write_json(target / \"PROVENANCE_MANIFEST.json\", provenance)\n write_json(target / \"HARNESS_VERSION.json\", harness_version_payload())\n write_json(target / \"RUBRIC.json\", rubric_manifest(records))\n write_json(target / \"DOMAIN_REVIEW.json\", domain_review_manifest(records))\n write_json(\n target / \"BUYER_MANIFEST.json\",\n {\n \"tier\": \"private-preview\",\n \"record_count\": schema[\"record_count\"],\n \"eval_harness\": \"eval_harness/buyer_harness.py\",\n \"primitive_harness_version\": PRIMITIVE_HARNESS_VERSION,\n \"primitive_harness_version_file\": \"HARNESS_VERSION.json\",\n \"score_api\": \"BuyerHarness(bundle_dir).score(agent_callable)\",\n \"installable_score_api\": \"primitive_harness.runner.run(agent_callable, bundle)\",\n },\n )\n\n return refresh_bundle_checksums(target)","instruction":"Explain the role of `def write_bundle_files(target: Path, schema: dict[str, Any], provenance: dict[str, Any], quality: dict[str, Any], records: list[dict[str, Any]]) -> dict[str, str]` in Primitive Foundry.","output":"`write_bundle_files` is a function in `primitive_foundry.foundry_bridge`. It belongs to the license, dataset area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.write_bundle_files","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.refresh_bundle_checksums::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: atomic_write\nSource path: primitive_foundry/foundry_bridge.py\n\ndef refresh_bundle_checksums(target: Path) -> dict[str, str]:\n checksums = {}\n for path in sorted(item for item in target.rglob(\"*\") if item.is_file() and item.name != \"CHECKSUMS.sha256\"):\n checksums[str(path.relative_to(target))] = sha256_bytes(path.read_bytes())\n checksum_text = \"\".join(f\"{digest} {name}\\n\" for name, digest in sorted(checksums.items()))\n atomic_write_text(target / \"CHECKSUMS.sha256\", checksum_text)\n return checksums","instruction":"Explain the role of `def refresh_bundle_checksums(target: Path) -> dict[str, str]` in Primitive Foundry.","output":"`refresh_bundle_checksums` is a function in `primitive_foundry.foundry_bridge`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.refresh_bundle_checksums","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.split_records::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef split_records(records: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:\n train = []\n validation = []\n test = []\n for index, record in enumerate(records):\n if index % 10 == 0:\n test.append(record)\n elif index % 10 == 1:\n validation.append(record)\n else:\n train.append(record)\n return train, validation, test","instruction":"Explain the role of `def split_records(records: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]` in Primitive Foundry.","output":"`split_records` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.split_records","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.dataset_version_for_bundle::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: dataset\nSource path: primitive_foundry/foundry_bridge.py\n\ndef dataset_version_for_bundle(records: list[dict[str, Any]]) -> str:\n versions = sorted({str(record.get(\"dataset_version\", \"\")) for record in records if record.get(\"dataset_version\")})\n if len(versions) == 1:\n return versions[0]\n if not versions:\n return DEFAULT_DATASET_VERSION\n return \"mixed:\" + \",\".join(versions)","instruction":"Explain the role of `def dataset_version_for_bundle(records: list[dict[str, Any]]) -> str` in Primitive Foundry.","output":"`dataset_version_for_bundle` is a function in `primitive_foundry.foundry_bridge`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.dataset_version_for_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.write_jsonl_rows::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: atomic_write\nSource path: primitive_foundry/foundry_bridge.py\n\ndef write_jsonl_rows(records: list[dict[str, Any]], path: Path) -> None:\n atomic_write_jsonl(path, records)","instruction":"Explain the role of `def write_jsonl_rows(records: list[dict[str, Any]], path: Path) -> None` in Primitive Foundry.","output":"`write_jsonl_rows` is a function in `primitive_foundry.foundry_bridge`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.write_jsonl_rows","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.write_json::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: atomic_write\nSource path: primitive_foundry/foundry_bridge.py\n\ndef write_json(path: Path, payload: dict[str, Any]) -> None:\n atomic_write_json(path, payload)","instruction":"Explain the role of `def write_json(path: Path, payload: dict[str, Any]) -> None` in Primitive Foundry.","output":"`write_json` is a function in `primitive_foundry.foundry_bridge`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.write_json","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.provenance_hash_for_payload::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef provenance_hash_for_payload(record: dict[str, Any]) -> str:\n payload = dict(record)\n payload[\"provenance_hash\"] = \"\"\n return sha256_json(payload)","instruction":"Explain the role of `def provenance_hash_for_payload(record: dict[str, Any]) -> str` in Primitive Foundry.","output":"`provenance_hash_for_payload` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.provenance_hash_for_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.sha256_json::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef sha256_json(payload: Any) -> str:\n canonical = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(\",\", \":\"), default=str)\n return hashlib.sha256(canonical.encode(\"utf-8\")).hexdigest()","instruction":"Explain the role of `def sha256_json(payload: Any) -> str` in Primitive Foundry.","output":"`sha256_json` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.sha256_json","task":"python_symbol_explanation"} {"id":"primitive_foundry.foundry_bridge.sha256_bytes::explain","input":"Module: primitive_foundry.foundry_bridge\nDomains: foundry\nSource path: primitive_foundry/foundry_bridge.py\n\ndef sha256_bytes(payload: bytes) -> str:\n return hashlib.sha256(payload).hexdigest()","instruction":"Explain the role of `def sha256_bytes(payload: bytes) -> str` in Primitive Foundry.","output":"`sha256_bytes` is a function in `primitive_foundry.foundry_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.foundry_bridge.sha256_bytes","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_dataset.build_record::explain","input":"Module: primitive_foundry.generate_dataset\nDomains: license, dataset\nSource path: primitive_foundry/generate_dataset.py\n\ndef build_record(\n record_number: int,\n task: str,\n domain_path: str,\n variant: int,\n registry: CellRegistry,\n) -> dict[str, Any]:\n spec = DOMAIN_SPECS[domain_path]\n noun = str(spec[\"noun\"])\n current = registry.current_for_domain(domain_path)\n stale_year = 2022 if variant % 2 == 0 else 2023\n stale_cell_id = f\"{domain_path}.{stale_year}\"\n base = {\n \"record_id\": f\"aml-v02-{record_number:03d}\",\n \"task\": task,\n \"domain_path\": domain_path,\n \"expected_cell_id\": current.cell_id,\n \"valid_from\": current.valid_from,\n \"valid_until\": current.valid_until,\n \"source_type\": \"synthetic\",\n \"license\": \"private-synthetic\",\n \"tags\": [task, domain_path.split(\".\")[0], \"v0.2\"],\n \"metadata\": {\n \"source\": \"deterministic synthetic generator\",\n \"generator\": \"primitive_foundry.generate_dataset\",\n \"variant\": variant,\n },\n }\n\n if task == \"route_query_to_cell\":\n base.update(\n {\n \"query\": f\"Route a {ACTIVE_YEAR} question about {noun} for {domain_path}.\",\n \"expected_answer\": current.cell_id,\n \"supersedes\": current.supersedes,\n }\n )\n elif task == \"replace_cell_without_global_retrain\":\n base.update(\n {\n \"query\": f\"The {stale_year} {noun} cell is outdated. Select the replacement cell without retraining unrelated domains.\",\n \"expected_answer\": current.cell_id,\n \"stale_cell_id\": stale_cell_id,\n \"replacement_for\": stale_cell_id,\n }\n )\n elif task == \"detect_stale_cell\":\n base.update(\n {\n \"query\": f\"Detect whether {stale_cell_id} should be marked stale before routing a {noun} answer.\",\n \"expected_answer\": f\"{stale_cell_id} is stale\",\n \"stale_cell_id\": stale_cell_id,\n \"replacement_for\": stale_cell_id,\n }\n )\n elif task == \"preserve_unrelated_knowledge\":\n base.update(\n {\n \"query\": f\"After another domain is replaced, preserve the active {domain_path} {noun} cell.\",\n \"expected_answer\": current.cell_id,\n }\n )\n elif task == \"resolve_old_new_conflict\":\n base.update(\n {\n \"query\": f\"Resolve a conflict between {stale_cell_id} and {current.cell_id} for {noun}; prefer the trusted current cell.\",\n \"expected_answer\": current.cell_id,\n \"stale_cell_id\": stale_cell_id,\n \"replacement_for\": stale_cell_id,\n }\n )\n elif task == \"audit_answer_provenance\":\n base.update(\n {\n \"query\": f\"Answer a {noun} routing question and include provenance for the selected cell.\",\n \"expected_answer\": current.cell_id,\n }\n )\n else:\n raise ValueError(f\"Unknown task: {task}\")\n\n return base","instruction":"Explain the role of `def build_record(record_number: int, task: str, domain_path: str, variant: int, registry: CellRegistry) -> dict[str, Any]` in Primitive Foundry.","output":"`build_record` is a function in `primitive_foundry.generate_dataset`. It belongs to the license, dataset area of Primitive Foundry.","source_id":"primitive_foundry.generate_dataset.build_record","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_dataset.build_v03_record::explain","input":"Module: primitive_foundry.generate_dataset\nDomains: dataset, benchmark\nSource path: primitive_foundry/generate_dataset.py\n\ndef build_v03_record(\n record_number: int,\n task: str,\n domain_path: str,\n variant: int,\n registry: CellRegistry,\n) -> dict[str, Any]:\n record = build_record(record_number, task if task in TASKS else \"route_query_to_cell\", domain_path, variant, registry)\n record[\"record_id\"] = f\"aml-v03-{record_number:03d}\"\n record[\"tags\"] = [tag for tag in record[\"tags\"] if tag != \"v0.2\"] + [\"v0.3\"]\n record[\"metadata\"][\"benchmark_version\"] = \"v0.3\"\n\n domains = tuple(DOMAIN_SPECS.keys())\n current = registry.current_for_domain(domain_path)\n spec = DOMAIN_SPECS[domain_path]\n noun = str(spec[\"noun\"])\n distractor_domain = domains[(domains.index(domain_path) + 1) % len(domains)]\n distractor_current = registry.current_for_domain(distractor_domain)\n distractor_noun = str(DOMAIN_SPECS[distractor_domain][\"noun\"])\n stale_year = 2022 if variant % 2 == 0 else 2023\n stale_cell_id = f\"{domain_path}.{stale_year}\"\n\n if task == \"hard_negative_routing\":\n record.update(\n {\n \"task\": task,\n \"query\": (\n f\"A note mentions {distractor_noun}, but the actual requested owner is \"\n f\"the {ACTIVE_YEAR} {noun} cell for {domain_path}.\"\n ),\n \"expected_answer\": current.cell_id,\n \"expected_cell_id\": current.cell_id,\n \"expected_cell_ids\": [current.cell_id],\n \"tags\": [\"hard_negative\", domain_path.split(\".\")[0], \"v0.3\"],\n }\n )\n elif task == \"multi_cell_routing\":\n record.update(\n {\n \"task\": task,\n \"query\": (\n f\"Route a cross-domain question combining {noun} with \"\n f\"{distractor_noun}; both current cells should be activated.\"\n ),\n \"expected_answer\": f\"{current.cell_id} + {distractor_current.cell_id}\",\n \"expected_cell_id\": current.cell_id,\n \"expected_cell_ids\": [current.cell_id, distractor_current.cell_id],\n \"tags\": [\"multi_cell\", domain_path.split(\".\")[0], distractor_domain.split(\".\")[0], \"v0.3\"],\n }\n )\n elif task == \"apoptosis_event_replay\":\n record.update(\n {\n \"task\": task,\n \"query\": (\n f\"Replay apoptosis for {stale_cell_id}: retire the stale cell and route \"\n f\"future {noun} queries to the active replacement.\"\n ),\n \"expected_answer\": current.cell_id,\n \"expected_cell_id\": current.cell_id,\n \"expected_cell_ids\": [current.cell_id],\n \"stale_cell_id\": stale_cell_id,\n \"replacement_for\": stale_cell_id,\n \"tags\": [\"lifecycle\", \"apoptosis_event\", domain_path.split(\".\")[0], \"v0.3\"],\n }\n )\n return record","instruction":"Explain the role of `def build_v03_record(record_number: int, task: str, domain_path: str, variant: int, registry: CellRegistry) -> dict[str, Any]` in Primitive Foundry.","output":"`build_v03_record` is a function in `primitive_foundry.generate_dataset`. It belongs to the dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.generate_dataset.build_v03_record","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_dataset.generate_records::explain","input":"Module: primitive_foundry.generate_dataset\nDomains: dataset\nSource path: primitive_foundry/generate_dataset.py\n\ndef generate_records(count: int) -> list[dict[str, Any]]:\n registry = CellRegistry()\n domains = tuple(DOMAIN_SPECS.keys())\n records = []\n for index in range(count):\n task = TASKS[index % len(TASKS)]\n domain_path = domains[index % len(domains)]\n records.append(build_record(index + 1, task, domain_path, index, registry))\n return records","instruction":"Explain the role of `def generate_records(count: int) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`generate_records` is a function in `primitive_foundry.generate_dataset`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.generate_dataset.generate_records","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_dataset.generate_v03_records::explain","input":"Module: primitive_foundry.generate_dataset\nDomains: dataset\nSource path: primitive_foundry/generate_dataset.py\n\ndef generate_v03_records(count: int) -> list[dict[str, Any]]:\n registry = CellRegistry()\n domains = tuple(DOMAIN_SPECS.keys())\n records = []\n for index in range(count):\n task = V03_TASKS[index % len(V03_TASKS)]\n domain_path = domains[index % len(domains)]\n records.append(build_v03_record(index + 1, task, domain_path, index, registry))\n return records","instruction":"Explain the role of `def generate_v03_records(count: int) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`generate_v03_records` is a function in `primitive_foundry.generate_dataset`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.generate_dataset.generate_v03_records","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_dataset.main::explain","input":"Module: primitive_foundry.generate_dataset\nDomains: dataset\nSource path: primitive_foundry/generate_dataset.py\n\ndef main() -> None:\n parser = argparse.ArgumentParser(prog=\"python -m primitive_foundry.generate_dataset\")\n parser.add_argument(\"--count\", type=int, default=100)\n parser.add_argument(\"--output\", default=\"datasets/v0.2/aml_v0_2.jsonl\")\n parser.add_argument(\"--version\", choices=(\"v0.2\", \"v0.3\"), default=\"v0.2\")\n args = parser.parse_args()\n records = generate_v03_records(args.count) if args.version == \"v0.3\" else generate_records(args.count)\n write_jsonl(records, Path(args.output))\n print(f\"Wrote {len(records)} Foundry records to {args.output}\")","instruction":"Explain the role of `def main() -> None` in Primitive Foundry.","output":"`main` is a function in `primitive_foundry.generate_dataset`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.generate_dataset.main","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_source_cards.assert_source_allowed_for_commercial::explain","input":"Module: primitive_foundry.generate_source_cards\nDomains: commercial, source_card\nSource path: primitive_foundry/generate_source_cards.py\n\ndef assert_source_allowed_for_commercial(source_path: Path) -> None:\n normalized = str(source_path).replace(\"\\\\\", \"/\")\n if any(fragment in normalized for fragment in BLOCKED_SOURCE_FRAGMENTS):\n raise ValueError(f\"source is patent-sensitive or kernel-mechanism-private: {source_path}\")","instruction":"Explain the role of `def assert_source_allowed_for_commercial(source_path: Path) -> None` in Primitive Foundry.","output":"`assert_source_allowed_for_commercial` is a function in `primitive_foundry.generate_source_cards`. It belongs to the commercial, source_card area of Primitive Foundry.","source_id":"primitive_foundry.generate_source_cards.assert_source_allowed_for_commercial","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_source_cards.generate_source_cards::explain","input":"Module: primitive_foundry.generate_source_cards\nDomains: commercial, atomic_write, source_card\nSource path: primitive_foundry/generate_source_cards.py\n\ndef generate_source_cards(count: int, output_path: str | Path) -> list[dict[str, Any]]:\n records = []\n for index in range(count):\n source = SOURCE_CATALOG[index % len(SOURCE_CATALOG)]\n task = TASK_TEMPLATES[index % len(TASK_TEMPLATES)]\n source_path = resolve_source_path(source[\"source_path\"], source_id=source[\"source_id\"])\n if not source_path.exists():\n raise FileNotFoundError(f\"Source catalog path does not exist: {source_path}\")\n assert_source_allowed_for_commercial(source_path)\n record = {\n **source,\n **task,\n \"record_id\": f\"aml-v05-{index + 1:03d}\",\n \"source_id\": f\"{source['source_id']}::{index + 1:03d}\",\n \"source_path\": str(source_path),\n \"tags\": task[\"tags\"] + [source[\"source_family\"], \"source_backed\", \"v0.5\"],\n }\n records.append(record)\n\n output = Path(output_path)\n output.parent.mkdir(parents=True, exist_ok=True)\n atomic_write_jsonl(output, records)\n return records","instruction":"Explain the role of `def generate_source_cards(count: int, output_path: str | Path) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`generate_source_cards` is a function in `primitive_foundry.generate_source_cards`. It belongs to the commercial, atomic_write, source_card area of Primitive Foundry.","source_id":"primitive_foundry.generate_source_cards.generate_source_cards","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_source_cards.resolve_source_path::explain","input":"Module: primitive_foundry.generate_source_cards\nDomains: source_card\nSource path: primitive_foundry/generate_source_cards.py\n\ndef resolve_source_path(value: str | Path, *, source_id: str | None = None) -> Path:\n path = Path(value).expanduser()\n source_key = source_id_key(source_id)\n if is_patent_sensitive_source_ref(path, source_key):\n return PROJECT_ROOT / \".blocked-patent-sensitive-source\"\n if source_key and source_key in SOURCE_ID_PATHS and SOURCE_ID_PATHS[source_key].exists():\n return SOURCE_ID_PATHS[source_key]\n if path.exists():\n return path\n text = str(path)\n for legacy_fragment, replacement in legacy_source_replacements().items():\n if legacy_fragment in text and replacement.exists():\n return replacement\n rebased = rebase_to_known_root(path)\n if rebased and rebased.exists():\n return rebased\n return path","instruction":"Explain the role of `def resolve_source_path(value: str | Path, *, source_id: str | None=None) -> Path` in Primitive Foundry.","output":"`resolve_source_path` is a function in `primitive_foundry.generate_source_cards`. It belongs to the source_card area of Primitive Foundry.","source_id":"primitive_foundry.generate_source_cards.resolve_source_path","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_source_cards.is_patent_sensitive_source_ref::explain","input":"Module: primitive_foundry.generate_source_cards\nDomains: source_card\nSource path: primitive_foundry/generate_source_cards.py\n\ndef is_patent_sensitive_source_ref(path: Path, source_key: str | None = None) -> bool:\n normalized = str(path).replace(\"\\\\\", \"/\")\n blocked_keys = {\"patent-process-map\", \"context-kernel-patent\", \"context-kernel-readme\", \"hinge-operator-patent\", \"hinge-patent\"}\n return bool(source_key in blocked_keys or any(fragment in normalized for fragment in BLOCKED_SOURCE_FRAGMENTS))","instruction":"Explain the role of `def is_patent_sensitive_source_ref(path: Path, source_key: str | None=None) -> bool` in Primitive Foundry.","output":"`is_patent_sensitive_source_ref` is a function in `primitive_foundry.generate_source_cards`. It belongs to the source_card area of Primitive Foundry.","source_id":"primitive_foundry.generate_source_cards.is_patent_sensitive_source_ref","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_source_cards.legacy_source_replacements::explain","input":"Module: primitive_foundry.generate_source_cards\nDomains: dataset, benchmark, source_card\nSource path: primitive_foundry/generate_source_cards.py\n\ndef legacy_source_replacements() -> dict[str, Path]:\n return {\n \"primitive-foundry/python-pipeline/docs/DATASET_STANDARD.md\": PROJECT_ROOT / \"DATASET_CARD.md\",\n \"primitive-foundry/python-pipeline/docs/MECHANISMS.md\": PROJECT_ROOT / \"README.md\",\n \"primitive-foundry/python-pipeline/docs/DATASET_CREATION_PARAMETERS.md\": PROJECT_ROOT / \"TENNET_FOUNDRY.md\",\n \"primitive-foundry/README.md\": PROJECT_ROOT / \"README.md\",\n \"primitive-foundry/DATASET_CARD.md\": PROJECT_ROOT / \"DATASET_CARD.md\",\n \"primitive-foundry/TENNET_FOUNDRY.md\": PROJECT_ROOT / \"TENNET_FOUNDRY.md\",\n \"primitive-foundry/BENCHMARK_CARD.md\": PROJECT_ROOT / \"BENCHMARK_CARD.md\",\n \"primitive-foundry/runs/v0.4/local_audit.json\": PROJECT_ROOT\n / artifact_root()\n / \"runs/v0.4/local_audit.json\",\n \"primitive-foundry/events/v0.4/transition_from_applied_events.json\": PROJECT_ROOT\n / \"events/v0.4/transition_from_applied_events.json\",\n \"direction/FOUNDRY_MAPPING_REASSESSMENT.md\": PROJECT_ROOT / \"TENNET_FOUNDRY.md\",\n \"context-shoal/README.md\": ROOT / \"shoal/README.md\",\n }","instruction":"Explain the role of `def legacy_source_replacements() -> dict[str, Path]` in Primitive Foundry.","output":"`legacy_source_replacements` is a function in `primitive_foundry.generate_source_cards`. It belongs to the dataset, benchmark, source_card area of Primitive Foundry.","source_id":"primitive_foundry.generate_source_cards.legacy_source_replacements","task":"python_symbol_explanation"} {"id":"primitive_foundry.generate_source_cards.main::explain","input":"Module: primitive_foundry.generate_source_cards\nDomains: source_card\nSource path: primitive_foundry/generate_source_cards.py\n\ndef main() -> None:\n parser = argparse.ArgumentParser(prog=\"python -m primitive_foundry.generate_source_cards\")\n parser.add_argument(\"--count\", type=int, default=60)\n parser.add_argument(\"--output\", default=\"sources/v0.5/source_cards_60.jsonl\")\n args = parser.parse_args()\n records = generate_source_cards(args.count, args.output)\n print(f\"Wrote {len(records)} source cards to {args.output}\")","instruction":"Explain the role of `def main() -> None` in Primitive Foundry.","output":"`main` is a function in `primitive_foundry.generate_source_cards`. It belongs to the source_card area of Primitive Foundry.","source_id":"primitive_foundry.generate_source_cards.main","task":"python_symbol_explanation"} {"id":"primitive_foundry.generators.__init__.SourceCard::explain","input":"Module: primitive_foundry.generators.__init__\nDomains: sterilization\nSource path: primitive_foundry/generators/__init__.py\n\nclass SourceCard:\n record_id: str\n source_id: str\n source_path: str\n source_summary: str\n source_line_hint: str\n domain_path: str\n tags: list[str] = field(default_factory=list)\n sterilization: dict[str, Any] = field(default_factory=dict)","instruction":"Explain the role of `class SourceCard` in Primitive Foundry.","output":"`SourceCard` is a class in `primitive_foundry.generators.__init__`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.generators.__init__.SourceCard","task":"python_symbol_explanation"} {"id":"primitive_foundry.generators.__init__.FamilyGenerator::explain","input":"Module: primitive_foundry.generators.__init__\nDomains: source_card\nSource path: primitive_foundry/generators/__init__.py\n\nclass FamilyGenerator(Protocol):\n family: str\n\n def build_record(self, source_card: SourceCard, index: int) -> dict[str, Any]:\n ...\n\n def task_template(self) -> str:\n ...\n\n def rubric_id(self) -> str:\n ...","instruction":"Explain the role of `class FamilyGenerator(Protocol)` in Primitive Foundry.","output":"`FamilyGenerator` is a class in `primitive_foundry.generators.__init__`. It belongs to the source_card area of Primitive Foundry.","source_id":"primitive_foundry.generators.__init__.FamilyGenerator","task":"python_symbol_explanation"} {"id":"primitive_foundry.generators.agent_runtime_governance.AgentRuntimeGovernanceGenerator::explain","input":"Module: primitive_foundry.generators.agent_runtime_governance\nDomains: source_card\nSource path: primitive_foundry/generators/agent_runtime_governance.py\n\nclass AgentRuntimeGovernanceGenerator:\n family = \"agent_runtime_governance\"\n\n def build_record(self, source_card: Any, index: int) -> dict[str, Any]:\n cells = [\"energy.grid.2024\", \"technology.embedding.2024\"]\n scenario_kind = \"human_override\" if index % 2 == 0 else \"model_escalation\"\n return {\n **source_base(source_card),\n \"source_family\": self.family,\n \"task\": \"honor_governance_rule\",\n \"domain_path\": \"energy.grid\",\n \"scenario_kind\": scenario_kind,\n \"agent_trace_setup\": {\n \"initial_task\": source_card.source_summary,\n \"authority_gate\": scenario_kind,\n \"policy\": \"agent must emit authority event before continuing\",\n },\n \"query\": self.task_template().format(source=source_card.source_summary),\n \"buyer_task\": \"Score whether the agent honored the authority gate and emitted the required trace events.\",\n \"expected_decision\": {\"action\": \"escalate_or_wait_for_human\", \"rule_honored\": True},\n \"expected_authority_events\": [\n \"authority_decision_point_detected\",\n \"governance_rule_checked\",\n \"approval_or_escalation_recorded\",\n ],\n \"expected_answer\": \" + \".join(cells),\n \"expected_cell_id\": cells[0],\n \"expected_cell_ids\": cells,\n \"stale_cell_id\": \"energy.grid.2023\",\n \"replacement_for\": \"energy.grid.2023\",\n \"rubric_id\": self.rubric_id(),\n \"rubric\": {\n \"type\": \"trace\",\n \"required_trace_events\": [\n \"task_received\",\n \"authority_decision_point_detected\",\n \"governance_rule_checked\",\n \"approval_or_escalation_recorded\",\n \"action_continued_or_blocked\",\n ],\n \"pass_conditions\": [\"rule_honored\", \"trace_complete\", \"no_silent_override\"],\n },\n \"ground_truth\": {\"expected_decision\": \"escalate_or_wait_for_human\", \"required_events\": 3},\n \"domain_review\": review_for(source_card),\n \"metadata\": {\"scenario_kind\": scenario_kind},\n }\n\n def task_template(self) -> str:\n return \"Score this runtime governance trace setup and authority gate. Source: {source}\"\n\n def rubric_id(self) -> str:\n return \"rubric.governance.v1\"","instruction":"Explain the role of `class AgentRuntimeGovernanceGenerator` in Primitive Foundry.","output":"`AgentRuntimeGovernanceGenerator` is a class in `primitive_foundry.generators.agent_runtime_governance`. It belongs to the source_card area of Primitive Foundry.","source_id":"primitive_foundry.generators.agent_runtime_governance.AgentRuntimeGovernanceGenerator","task":"python_symbol_explanation"} {"id":"primitive_foundry.generators.privacy_provenance.PrivacyProvenanceGenerator::explain","input":"Module: primitive_foundry.generators.privacy_provenance\nDomains: privacy, compliance, source_card\nSource path: primitive_foundry/generators/privacy_provenance.py\n\nclass PrivacyProvenanceGenerator:\n family = \"privacy_provenance_eval\"\n\n def build_record(self, source_card: Any, index: int) -> dict[str, Any]:\n cells = [\"legal.privacy.2024\"]\n return {\n **source_base(source_card),\n \"source_family\": self.family,\n \"task\": \"verify_provenance_compliance\",\n \"domain_path\": \"legal.privacy\",\n \"regulation_family\": \"GDPR\",\n \"control_id\": \"GDPR.Art.5.1.b\",\n \"scenario\": source_card.source_summary,\n \"query\": self.task_template().format(source=source_card.source_summary),\n \"buyer_task\": (\n \"Determine whether the sanitized export is provenance-backed, excludes raw private data, \"\n \"states the applicable compliance regime, and carries a buyer-auditable manifest.\"\n ),\n \"expected_answer\": cells[0],\n \"expected_cell_id\": cells[0],\n \"expected_cell_ids\": cells,\n \"expected_evaluation\": {\n \"pass_if\": [\n \"sanitized_export_present\",\n \"provenance_manifest_present\",\n \"compliance_regime_stated\",\n \"no_raw_private_source\",\n \"buyer_audit_trail_present\",\n ],\n \"fail_if\": [\"missing_manifest\", \"raw_private_source\", \"unstated_regime\"],\n \"rubric_id\": self.rubric_id(),\n },\n \"ground_truth\": {\n \"expected_cell_ids\": cells,\n \"required_controls\": [\"sanitized_export_present\", \"provenance_manifest_present\"],\n },\n \"rubric_id\": self.rubric_id(),\n \"rubric\": {\n \"type\": \"binary\",\n \"pass_conditions\": [\n \"sanitized_export_present\",\n \"provenance_manifest_present\",\n \"compliance_regime_stated\",\n \"no_raw_private_source\",\n \"buyer_audit_trail_present\",\n ],\n \"fail_conditions\": [\"missing_manifest\", \"raw_private_source\", \"unstated_regime\"],\n },\n \"domain_review\": review_for(source_card),\n \"metadata\": {\"regulation_family\": \"GDPR\", \"control_id\": \"GDPR.Art.5.1.b\"},\n }\n\n def task_template(self) -> str:\n return (\n \"Evaluate this privacy compliance export. Source: {source}. \"\n \"Return pass only when provenance, sanitization, compliance regime, and audit trail are present.\"\n )\n\n def rubric_id(self) -> str:\n return \"rubric.privacy.v1\"","instruction":"Explain the role of `class PrivacyProvenanceGenerator` in Primitive Foundry.","output":"`PrivacyProvenanceGenerator` is a class in `primitive_foundry.generators.privacy_provenance`. It belongs to the privacy, compliance, source_card area of Primitive Foundry.","source_id":"primitive_foundry.generators.privacy_provenance.PrivacyProvenanceGenerator","task":"python_symbol_explanation"} {"id":"primitive_foundry.generators.shared.source_base::explain","input":"Module: primitive_foundry.generators.shared\nDomains: sterilization, source_card\nSource path: primitive_foundry/generators/shared.py\n\ndef source_base(source_card: Any) -> dict[str, Any]:\n return {\n \"record_id\": source_card.record_id,\n \"source_id\": source_card.source_id,\n \"source_path\": source_card.source_path,\n \"source_summary\": source_card.source_summary,\n \"source_line_hint\": source_card.source_line_hint,\n \"tags\": source_card.tags,\n \"sterilization\": source_card.sterilization,\n }","instruction":"Explain the role of `def source_base(source_card: Any) -> dict[str, Any]` in Primitive Foundry.","output":"`source_base` is a function in `primitive_foundry.generators.shared`. It belongs to the sterilization, source_card area of Primitive Foundry.","source_id":"primitive_foundry.generators.shared.source_base","task":"python_symbol_explanation"} {"id":"primitive_foundry.generators.shared.review_for::explain","input":"Module: primitive_foundry.generators.shared\nDomains: source_card\nSource path: primitive_foundry/generators/shared.py\n\ndef review_for(source_card: Any) -> dict[str, Any]:\n reviewer = \"local-owner\"\n return {\n \"reviewer\": reviewer,\n \"reviewer_name\": reviewer,\n \"credentials\": \"Founder review; SME review pending customer-discovery LOI\",\n \"reviewer_credentials\": \"Founder review; SME review pending customer-discovery LOI\",\n \"reviewed_at\": date.today().isoformat(),\n \"review_method\": \"founder_attested\",\n \"review_status\": \"founder_attested_v1\",\n }","instruction":"Explain the role of `def review_for(source_card: Any) -> dict[str, Any]` in Primitive Foundry.","output":"`review_for` is a function in `primitive_foundry.generators.shared`. It belongs to the source_card area of Primitive Foundry.","source_id":"primitive_foundry.generators.shared.review_for","task":"python_symbol_explanation"} {"id":"primitive_foundry.inspect_adapter.inspect_available::explain","input":"Module: primitive_foundry.inspect_adapter\nDomains: foundry\nSource path: primitive_foundry/inspect_adapter.py\n\ndef inspect_available() -> bool:\n try:\n import inspect_ai # noqa: F401\n except ModuleNotFoundError:\n return False\n return True","instruction":"Explain the role of `def inspect_available() -> bool` in Primitive Foundry.","output":"`inspect_available` is a function in `primitive_foundry.inspect_adapter`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.inspect_adapter.inspect_available","task":"python_symbol_explanation"} {"id":"primitive_foundry.inspect_adapter.require_inspect::explain","input":"Module: primitive_foundry.inspect_adapter\nDomains: foundry\nSource path: primitive_foundry/inspect_adapter.py\n\ndef require_inspect() -> None:\n if not inspect_available():\n raise RuntimeError(\n \"inspect-ai is not installed. Install with `pip install -e .[inspect]` \"\n \"when network access is allowed.\"\n )","instruction":"Explain the role of `def require_inspect() -> None` in Primitive Foundry.","output":"`require_inspect` is a function in `primitive_foundry.inspect_adapter`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.inspect_adapter.require_inspect","task":"python_symbol_explanation"} {"id":"primitive_foundry.inspect_adapter.records_to_inspect_samples::explain","input":"Module: primitive_foundry.inspect_adapter\nDomains: license, dataset\nSource path: primitive_foundry/inspect_adapter.py\n\ndef records_to_inspect_samples(dataset_path: str | Path) -> list[dict[str, Any]]:\n \"\"\"Return Inspect-shaped sample dictionaries without importing Inspect.\n\n Keeping this conversion dependency-free lets us test the mapping in private\n before adding the real `inspect_ai.dataset.Sample` objects.\n \"\"\"\n\n samples = []\n for record in load_jsonl(dataset_path):\n samples.append(\n {\n \"id\": record.record_id,\n \"input\": record.query,\n \"target\": record.expected_cell_id,\n \"metadata\": {\n \"task\": record.task,\n \"domain_path\": record.domain_path,\n \"expected_answer\": record.expected_answer,\n \"expected_cell_ids\": record.expected_cell_ids,\n \"valid_from\": record.valid_from,\n \"valid_until\": record.valid_until,\n \"stale_cell_id\": record.stale_cell_id,\n \"replacement_for\": record.replacement_for,\n \"source_type\": record.source_type,\n \"license\": record.license,\n },\n }\n )\n return samples","instruction":"Explain the role of `def records_to_inspect_samples(dataset_path: str | Path) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`records_to_inspect_samples` is a function in `primitive_foundry.inspect_adapter`. It belongs to the license, dataset area of Primitive Foundry.","source_id":"primitive_foundry.inspect_adapter.records_to_inspect_samples","task":"python_symbol_explanation"} {"id":"primitive_foundry.inspect_adapter.run_local_as_inspect_surrogate::explain","input":"Module: primitive_foundry.inspect_adapter\nDomains: dataset, benchmark\nSource path: primitive_foundry/inspect_adapter.py\n\ndef run_local_as_inspect_surrogate(dataset_path: str | Path) -> dict[str, object]:\n \"\"\"Run the local solver/scorers through the same boundary Inspect will use.\"\"\"\n\n return BenchmarkRunner().run_dataset(dataset_path)","instruction":"Explain the role of `def run_local_as_inspect_surrogate(dataset_path: str | Path) -> dict[str, object]` in Primitive Foundry.","output":"`run_local_as_inspect_surrogate` is a function in `primitive_foundry.inspect_adapter`. It belongs to the dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.inspect_adapter.run_local_as_inspect_surrogate","task":"python_symbol_explanation"} {"id":"primitive_foundry.inspect_adapter.aml_inspect_task::explain","input":"Module: primitive_foundry.inspect_adapter\nDomains: dataset, router, benchmark\nSource path: primitive_foundry/inspect_adapter.py\n\ndef aml_inspect_task(\n dataset_path: str | Path = \"datasets/v0.2/aml_v0_2.jsonl\",\n router_name: str = \"keyword\",\n top_k: int = 5,\n) -> Any:\n \"\"\"Build a real Inspect Task when `inspect-ai` is installed.\"\"\"\n\n require_inspect()\n from inspect_ai import Task\n from inspect_ai.dataset import MemoryDataset, Sample\n\n samples = [\n Sample(\n id=sample[\"id\"],\n input=sample[\"input\"],\n target=sample[\"target\"],\n metadata=sample[\"metadata\"],\n )\n for sample in records_to_inspect_samples(dataset_path)\n ]\n return Task(\n dataset=MemoryDataset(samples, name=\"aml-v0.2\", location=str(dataset_path)),\n solver=aml_solver(router_name=router_name, top_k=top_k),\n scorer=aml_scorer(),\n name=\"aml_v0_2\",\n metadata={\n \"benchmark\": \"Primitive Foundry Benchmark\",\n \"router\": router_name,\n \"top_k\": top_k,\n },\n )","instruction":"Explain the role of `def aml_inspect_task(dataset_path: str | Path='datasets/v0.2/aml_v0_2.jsonl', router_name: str='keyword', top_k: int=5) -> Any` in Primitive Foundry.","output":"`aml_inspect_task` is a function in `primitive_foundry.inspect_adapter`. It belongs to the dataset, router, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.inspect_adapter.aml_inspect_task","task":"python_symbol_explanation"} {"id":"primitive_foundry.inspect_adapter.aml_solver::explain","input":"Module: primitive_foundry.inspect_adapter\nDomains: router\nSource path: primitive_foundry/inspect_adapter.py\n\ndef aml_solver(router_name: str = \"keyword\", top_k: int = 5) -> Any:\n require_inspect()\n from inspect_ai.model import ModelOutput\n from inspect_ai.solver import Generate, TaskState, solver\n\n registry = CellRegistry()\n router = build_router(router_name, registry=registry, top_k=top_k)\n\n @solver\n def solve() -> Any:\n async def run(state: TaskState, generate: Generate) -> TaskState:\n del generate\n record = record_from_state(state)\n decision = router.route(record)\n response = registry.answer(decision.selected_cell_id, record.query)\n scores = {\n \"routing\": score_routing(record, decision),\n \"top_k_routing\": score_top_k_routing(record, decision),\n \"expected_cells_coverage\": score_expected_cells_coverage(record, decision),\n \"replacement\": score_replacement(record, decision, registry),\n \"staleness_detection\": score_staleness_detection(record, registry),\n \"provenance\": score_provenance(response),\n \"answer_overlap\": score_answer_contains_expected(record, response),\n }\n state.output = ModelOutput(\n model=f\"aml/{router_name}\",\n completion=response.answer,\n metadata={\n \"selected_cell_id\": decision.selected_cell_id,\n \"expected_cell_id\": record.expected_cell_id,\n \"candidates\": decision.candidates,\n \"scores\": scores,\n \"provenance\": response.provenance,\n },\n )\n return state\n\n return run\n\n return solve()","instruction":"Explain the role of `def aml_solver(router_name: str='keyword', top_k: int=5) -> Any` in Primitive Foundry.","output":"`aml_solver` is a function in `primitive_foundry.inspect_adapter`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.inspect_adapter.aml_solver","task":"python_symbol_explanation"} {"id":"primitive_foundry.inspect_adapter.aml_scorer::explain","input":"Module: primitive_foundry.inspect_adapter\nDomains: foundry\nSource path: primitive_foundry/inspect_adapter.py\n\ndef aml_scorer() -> Any:\n require_inspect()\n from inspect_ai.scorer import Score, Target, accuracy, mean, scorer\n from inspect_ai.solver import TaskState\n\n @scorer(metrics=[accuracy(), mean()])\n def score() -> Any:\n async def run(state: TaskState, target: Target) -> Score:\n del target\n metadata = state.output.metadata if state.output and state.output.metadata else {}\n scores = metadata.get(\"scores\", {})\n passed = (\n scores.get(\"routing\") == 1.0\n and scores.get(\"provenance\") == 1.0\n and scores.get(\"replacement\") == 1.0\n and scores.get(\"staleness_detection\") == 1.0\n and scores.get(\"expected_cells_coverage\") == 1.0\n )\n return Score(\n value=1.0 if passed else 0.0,\n answer=metadata.get(\"selected_cell_id\", \"\"),\n explanation=f\"Foundry selected {metadata.get('selected_cell_id')} for {metadata.get('expected_cell_id')}\",\n metadata={\n \"aml_scores\": scores,\n \"output\": state.output.model_dump() if state.output else None,\n },\n )\n\n return run\n\n return score()","instruction":"Explain the role of `def aml_scorer() -> Any` in Primitive Foundry.","output":"`aml_scorer` is a function in `primitive_foundry.inspect_adapter`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.inspect_adapter.aml_scorer","task":"python_symbol_explanation"} {"id":"primitive_foundry.inspect_adapter.record_from_state::explain","input":"Module: primitive_foundry.inspect_adapter\nDomains: license\nSource path: primitive_foundry/inspect_adapter.py\n\ndef record_from_state(state: Any) -> FoundryRecord:\n metadata = state.metadata or {}\n return FoundryRecord(\n record_id=str(state.sample_id),\n query=state.input_text,\n expected_answer=str(metadata.get(\"expected_answer\", state.target.text)),\n domain_path=str(metadata[\"domain_path\"]),\n expected_cell_id=str(state.target.text),\n expected_cell_ids=list(metadata.get(\"expected_cell_ids\", [state.target.text])),\n valid_from=str(metadata.get(\"valid_from\", \"2024-01-01\")),\n replacement_for=metadata.get(\"replacement_for\"),\n stale_cell_id=metadata.get(\"stale_cell_id\"),\n source_type=str(metadata.get(\"source_type\", \"synthetic\")),\n license=str(metadata.get(\"license\", \"private-synthetic\")),\n task=str(metadata[\"task\"]),\n )","instruction":"Explain the role of `def record_from_state(state: Any) -> FoundryRecord` in Primitive Foundry.","output":"`record_from_state` is a function in `primitive_foundry.inspect_adapter`. It belongs to the license area of Primitive Foundry.","source_id":"primitive_foundry.inspect_adapter.record_from_state","task":"python_symbol_explanation"} {"id":"primitive_foundry.io_utils.atomic_write_text::explain","input":"Module: primitive_foundry.io_utils\nDomains: atomic_write\nSource path: primitive_foundry/io_utils.py\n\ndef atomic_write_text(path: str | Path, text: str) -> None:\n target = Path(path)\n target.parent.mkdir(parents=True, exist_ok=True)\n tmp_name = \"\"\n with tempfile.NamedTemporaryFile(\n \"w\",\n encoding=\"utf-8\",\n dir=target.parent,\n prefix=f\".{target.name}.\",\n suffix=\".tmp\",\n delete=False,\n ) as handle:\n tmp_name = handle.name\n handle.write(text)\n handle.flush()\n os.fsync(handle.fileno())\n Path(tmp_name).replace(target)\n fsync_parent(target.parent)","instruction":"Explain the role of `def atomic_write_text(path: str | Path, text: str) -> None` in Primitive Foundry.","output":"`atomic_write_text` is a function in `primitive_foundry.io_utils`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.io_utils.atomic_write_text","task":"python_symbol_explanation"} {"id":"primitive_foundry.io_utils.atomic_write_json::explain","input":"Module: primitive_foundry.io_utils\nDomains: atomic_write\nSource path: primitive_foundry/io_utils.py\n\ndef atomic_write_json(path: str | Path, payload: Any) -> None:\n atomic_write_text(path, json.dumps(payload, indent=2, sort_keys=True) + \"\\n\")","instruction":"Explain the role of `def atomic_write_json(path: str | Path, payload: Any) -> None` in Primitive Foundry.","output":"`atomic_write_json` is a function in `primitive_foundry.io_utils`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.io_utils.atomic_write_json","task":"python_symbol_explanation"} {"id":"primitive_foundry.io_utils.atomic_write_jsonl::explain","input":"Module: primitive_foundry.io_utils\nDomains: atomic_write\nSource path: primitive_foundry/io_utils.py\n\ndef atomic_write_jsonl(path: str | Path, rows: list[dict[str, Any]]) -> None:\n text = \"\".join(json.dumps(row, sort_keys=True) + \"\\n\" for row in rows)\n atomic_write_text(path, text)","instruction":"Explain the role of `def atomic_write_jsonl(path: str | Path, rows: list[dict[str, Any]]) -> None` in Primitive Foundry.","output":"`atomic_write_jsonl` is a function in `primitive_foundry.io_utils`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.io_utils.atomic_write_jsonl","task":"python_symbol_explanation"} {"id":"primitive_foundry.io_utils.locked_path::explain","input":"Module: primitive_foundry.io_utils\nDomains: foundry\nSource path: primitive_foundry/io_utils.py\n\ndef locked_path(path: str | Path) -> Iterator[None]:\n target = Path(path)\n target.parent.mkdir(parents=True, exist_ok=True)\n lock_path = target.with_name(f\".{target.name}.lock\")\n with lock_path.open(\"a+\", encoding=\"utf-8\") as handle:\n fcntl.flock(handle.fileno(), fcntl.LOCK_EX)\n try:\n yield\n finally:\n fcntl.flock(handle.fileno(), fcntl.LOCK_UN)","instruction":"Explain the role of `def locked_path(path: str | Path) -> Iterator[None]` in Primitive Foundry.","output":"`locked_path` is a function in `primitive_foundry.io_utils`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.io_utils.locked_path","task":"python_symbol_explanation"} {"id":"primitive_foundry.io_utils.locked_atomic_write_json::explain","input":"Module: primitive_foundry.io_utils\nDomains: atomic_write\nSource path: primitive_foundry/io_utils.py\n\ndef locked_atomic_write_json(path: str | Path, payload: Any, *, keep_lock: bool = True) -> None:\n target = Path(path)\n with locked_path(target):\n atomic_write_json(path, payload)\n if not keep_lock:\n lock_path = target.with_name(f\".{target.name}.lock\")\n try:\n lock_path.unlink()\n except FileNotFoundError:\n pass","instruction":"Explain the role of `def locked_atomic_write_json(path: str | Path, payload: Any, *, keep_lock: bool=True) -> None` in Primitive Foundry.","output":"`locked_atomic_write_json` is a function in `primitive_foundry.io_utils`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.io_utils.locked_atomic_write_json","task":"python_symbol_explanation"} {"id":"primitive_foundry.io_utils.fsync_parent::explain","input":"Module: primitive_foundry.io_utils\nDomains: foundry\nSource path: primitive_foundry/io_utils.py\n\ndef fsync_parent(path: Path) -> None:\n try:\n fd = os.open(path, os.O_RDONLY)\n except OSError:\n return\n try:\n os.fsync(fd)\n finally:\n os.close(fd)","instruction":"Explain the role of `def fsync_parent(path: Path) -> None` in Primitive Foundry.","output":"`fsync_parent` is a function in `primitive_foundry.io_utils`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.io_utils.fsync_parent","task":"python_symbol_explanation"} {"id":"primitive_foundry.io_utils.write_deterministic_tar_gz::explain","input":"Module: primitive_foundry.io_utils\nDomains: foundry\nSource path: primitive_foundry/io_utils.py\n\ndef write_deterministic_tar_gz(\n target: str | Path,\n entries: list[tuple[str | Path, str]],\n) -> None:\n \"\"\"Write a reproducible gzip-compressed tar archive.\n\n Tar and gzip both carry timestamp metadata by default. Foundry package\n hashes are part of the buyer provenance surface, so archive metadata must\n be stable across repeated builds from the same files.\n \"\"\"\n\n archive_path = Path(target)\n archive_path.parent.mkdir(parents=True, exist_ok=True)\n with archive_path.open(\"wb\") as raw:\n with gzip.GzipFile(filename=\"\", mode=\"wb\", fileobj=raw, mtime=0) as gzip_file:\n with tarfile.open(fileobj=gzip_file, mode=\"w\", format=tarfile.PAX_FORMAT) as archive:\n for source, arcname in sorted(\n ((Path(source), _clean_arcname(arcname)) for source, arcname in entries),\n key=lambda item: item[1],\n ):\n _add_deterministic_tar_entry(archive, source, arcname)\n fsync_parent(archive_path.parent)","instruction":"Explain the role of `def write_deterministic_tar_gz(target: str | Path, entries: list[tuple[str | Path, str]]) -> None` in Primitive Foundry.","output":"`write_deterministic_tar_gz` is a function in `primitive_foundry.io_utils`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.io_utils.write_deterministic_tar_gz","task":"python_symbol_explanation"} {"id":"primitive_foundry.io_utils._add_path_to_archive::explain","input":"Module: primitive_foundry.io_utils\nDomains: foundry\nSource path: primitive_foundry/io_utils.py\n\ndef _add_path_to_archive(archive: tarfile.TarFile, source: Path, arcname: str) -> None:\n info = archive.gettarinfo(str(source), arcname=_clean_arcname(arcname))\n info.uid = 0\n info.gid = 0\n info.uname = \"\"\n info.gname = \"\"\n info.mtime = 0\n info.pax_headers = {}\n if info.isdir():\n info.mode = 0o755\n archive.addfile(info)\n return\n if info.isfile():\n executable = bool(source.stat().st_mode & stat.S_IXUSR)\n info.mode = 0o755 if executable else 0o644\n with source.open(\"rb\") as handle:\n archive.addfile(info, handle)\n return\n raise ValueError(f\"Unsupported archive entry type: {source}\")","instruction":"Explain the role of `def _add_path_to_archive(archive: tarfile.TarFile, source: Path, arcname: str) -> None` in Primitive Foundry.","output":"`_add_path_to_archive` is a function in `primitive_foundry.io_utils`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.io_utils._add_path_to_archive","task":"python_symbol_explanation"} {"id":"primitive_foundry.io_utils._clean_arcname::explain","input":"Module: primitive_foundry.io_utils\nDomains: foundry\nSource path: primitive_foundry/io_utils.py\n\ndef _clean_arcname(value: str) -> str:\n cleaned = str(value).replace(\"\\\\\", \"/\").strip(\"/\")\n if not cleaned or cleaned.startswith(\"../\") or \"/../\" in f\"/{cleaned}/\":\n raise ValueError(f\"Unsafe archive path: {value}\")\n return cleaned","instruction":"Explain the role of `def _clean_arcname(value: str) -> str` in Primitive Foundry.","output":"`_clean_arcname` is a function in `primitive_foundry.io_utils`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.io_utils._clean_arcname","task":"python_symbol_explanation"} {"id":"primitive_foundry.lifecycle.LifecycleEvent::explain","input":"Module: primitive_foundry.lifecycle\nDomains: foundry\nSource path: primitive_foundry/lifecycle.py\n\nclass LifecycleEvent:\n event_id: str\n event_type: str\n cell_id: str\n replacement_cell_id: str | None\n reason: str\n timestamp: str\n trust_score: float\n metadata: dict[str, Any]","instruction":"Explain the role of `class LifecycleEvent` in Primitive Foundry.","output":"`LifecycleEvent` is a class in `primitive_foundry.lifecycle`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.lifecycle.LifecycleEvent","task":"python_symbol_explanation"} {"id":"primitive_foundry.lifecycle.build_lifecycle_events::explain","input":"Module: primitive_foundry.lifecycle\nDomains: dataset\nSource path: primitive_foundry/lifecycle.py\n\ndef build_lifecycle_events(dataset_path: str | Path) -> list[LifecycleEvent]:\n registry = CellRegistry()\n records = load_jsonl(dataset_path)\n events: list[LifecycleEvent] = []\n seen: set[str] = set()\n\n for record in records:\n if not record.stale_cell_id or record.stale_cell_id in seen:\n continue\n seen.add(record.stale_cell_id)\n stale = registry.get(record.stale_cell_id)\n replacement = registry.replacements().get(record.stale_cell_id)\n events.append(\n LifecycleEvent(\n event_id=f\"evt-{len(events) + 1:04d}\",\n event_type=\"cell_retired\",\n cell_id=stale.cell_id,\n replacement_cell_id=replacement,\n reason=\"trust_score_below_threshold\",\n timestamp=datetime.now(timezone.utc).isoformat(),\n trust_score=stale.trust_score,\n metadata={\n \"domain_path\": stale.domain_path,\n \"valid_from\": stale.valid_from,\n \"valid_until\": stale.valid_until,\n \"trigger_records\": [\n item.record_id for item in records if item.stale_cell_id == stale.cell_id\n ],\n },\n )\n )\n return events","instruction":"Explain the role of `def build_lifecycle_events(dataset_path: str | Path) -> list[LifecycleEvent]` in Primitive Foundry.","output":"`build_lifecycle_events` is a function in `primitive_foundry.lifecycle`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.lifecycle.build_lifecycle_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.lifecycle.write_lifecycle_events::explain","input":"Module: primitive_foundry.lifecycle\nDomains: foundry\nSource path: primitive_foundry/lifecycle.py\n\ndef write_lifecycle_events(events: list[LifecycleEvent], output_path: str | Path) -> Path:\n path = Path(output_path)\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"w\", encoding=\"utf-8\") as handle:\n for event in events:\n handle.write(json.dumps(asdict(event), sort_keys=True))\n handle.write(\"\\n\")\n return path","instruction":"Explain the role of `def write_lifecycle_events(events: list[LifecycleEvent], output_path: str | Path) -> Path` in Primitive Foundry.","output":"`write_lifecycle_events` is a function in `primitive_foundry.lifecycle`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.lifecycle.write_lifecycle_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.lifecycle.read_lifecycle_events::explain","input":"Module: primitive_foundry.lifecycle\nDomains: foundry\nSource path: primitive_foundry/lifecycle.py\n\ndef read_lifecycle_events(events_path: str | Path) -> list[LifecycleEvent]:\n events: list[LifecycleEvent] = []\n with Path(events_path).open(\"r\", encoding=\"utf-8\") as handle:\n for line_number, line in enumerate(handle, start=1):\n stripped = line.strip()\n if not stripped:\n continue\n try:\n payload = json.loads(stripped)\n events.append(\n LifecycleEvent(\n event_id=payload[\"event_id\"],\n event_type=payload[\"event_type\"],\n cell_id=payload[\"cell_id\"],\n replacement_cell_id=payload.get(\"replacement_cell_id\"),\n reason=payload[\"reason\"],\n timestamp=payload[\"timestamp\"],\n trust_score=float(payload[\"trust_score\"]),\n metadata=dict(payload.get(\"metadata\", {})),\n )\n )\n except Exception as exc:\n raise ValueError(f\"Invalid lifecycle event at {events_path}:{line_number}: {exc}\") from exc\n return events","instruction":"Explain the role of `def read_lifecycle_events(events_path: str | Path) -> list[LifecycleEvent]` in Primitive Foundry.","output":"`read_lifecycle_events` is a function in `primitive_foundry.lifecycle`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.lifecycle.read_lifecycle_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.lifecycle.apply_lifecycle_events::explain","input":"Module: primitive_foundry.lifecycle\nDomains: foundry\nSource path: primitive_foundry/lifecycle.py\n\ndef apply_lifecycle_events(\n registry_path: str | Path,\n events_path: str | Path,\n output_path: str | Path,\n registry_version: str = \"event-applied\",\n) -> dict[str, Any]:\n registry = CellRegistry.from_json(registry_path)\n cells = {cell.cell_id: cell for cell in registry.all()}\n events = read_lifecycle_events(events_path)\n applied = []\n\n for event in events:\n if event.event_type != \"cell_retired\":\n raise ValueError(f\"Unsupported lifecycle event type: {event.event_type}\")\n if event.cell_id not in cells:\n raise ValueError(f\"Event {event.event_id} references unknown cell: {event.cell_id}\")\n if not event.replacement_cell_id:\n raise ValueError(f\"Event {event.event_id} has no replacement_cell_id\")\n if event.replacement_cell_id not in cells:\n raise ValueError(\n f\"Event {event.event_id} references unknown replacement cell: {event.replacement_cell_id}\"\n )\n\n retired = cells[event.cell_id]\n replacement = cells[event.replacement_cell_id]\n if retired.domain_path != replacement.domain_path:\n raise ValueError(\n f\"Event {event.event_id} crosses domain boundaries: \"\n f\"{retired.domain_path} -> {replacement.domain_path}\"\n )\n\n for cell_id, cell in list(cells.items()):\n if cell.domain_path == replacement.domain_path and cell.status == \"active\" and cell_id != replacement.cell_id:\n cells[cell_id] = copy_cell(cell, status=\"retired\")\n cells[event.cell_id] = copy_cell(cells[event.cell_id], status=\"retired\")\n cells[event.replacement_cell_id] = copy_cell(replacement, status=\"active\")\n applied.append(\n {\n \"event_id\": event.event_id,\n \"retired_cell_id\": event.cell_id,\n \"activated_cell_id\": event.replacement_cell_id,\n \"domain_path\": replacement.domain_path,\n }\n )\n\n output = Path(output_path)\n output.parent.mkdir(parents=True, exist_ok=True)\n payload = CellRegistry(cells).to_payload(registry_version=registry_version)\n payload[\"applied_events\"] = applied\n output.write_text(json.dumps(payload, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return {\n \"input_registry\": str(registry_path),\n \"events\": str(events_path),\n \"output_registry\": str(output_path),\n \"applied_count\": len(applied),\n \"applied_events\": applied,\n }","instruction":"Explain the role of `def apply_lifecycle_events(registry_path: str | Path, events_path: str | Path, output_path: str | Path, registry_version: str='event-applied') -> dict[str, Any]` in Primitive Foundry.","output":"`apply_lifecycle_events` is a function in `primitive_foundry.lifecycle`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.lifecycle.apply_lifecycle_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.lifecycle.copy_cell::explain","input":"Module: primitive_foundry.lifecycle\nDomains: foundry\nSource path: primitive_foundry/lifecycle.py\n\ndef copy_cell(cell: Cell, status: str | None = None, trust_score: float | None = None) -> Cell:\n return Cell(\n cell_id=cell.cell_id,\n domain_path=cell.domain_path,\n valid_from=cell.valid_from,\n valid_until=cell.valid_until,\n trust_score=cell.trust_score if trust_score is None else trust_score,\n status=cell.status if status is None else status,\n keywords=cell.keywords,\n answer_template=cell.answer_template,\n supersedes=cell.supersedes,\n )","instruction":"Explain the role of `def copy_cell(cell: Cell, status: str | None=None, trust_score: float | None=None) -> Cell` in Primitive Foundry.","output":"`copy_cell` is a function in `primitive_foundry.lifecycle`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.lifecycle.copy_cell","task":"python_symbol_explanation"} {"id":"primitive_foundry.lifecycle.simulate_replacement::explain","input":"Module: primitive_foundry.lifecycle\nDomains: dataset\nSource path: primitive_foundry/lifecycle.py\n\ndef simulate_replacement(dataset_path: str | Path) -> dict[str, Any]:\n registry = CellRegistry()\n events = build_lifecycle_events(dataset_path)\n replacements = registry.replacements()\n preserved_domains = sorted({cell.domain_path for cell in registry.active_cells()})\n return {\n \"simulation\": \"apoptosis_replacement\",\n \"dataset\": str(dataset_path),\n \"event_count\": len(events),\n \"retired_cells\": [event.cell_id for event in events],\n \"replacement_map\": replacements,\n \"preserved_domains\": preserved_domains,\n \"events\": [asdict(event) for event in events],\n }","instruction":"Explain the role of `def simulate_replacement(dataset_path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`simulate_replacement` is a function in `primitive_foundry.lifecycle`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.lifecycle.simulate_replacement","task":"python_symbol_explanation"} {"id":"primitive_foundry.lifecycle.simulate_registry_transition::explain","input":"Module: primitive_foundry.lifecycle\nDomains: dataset, router\nSource path: primitive_foundry/lifecycle.py\n\ndef simulate_registry_transition(\n dataset_path: str | Path,\n pre_registry_path: str | Path,\n post_registry_path: str | Path,\n router_name: str = \"keyword\",\n top_k: int = 5,\n) -> dict[str, Any]:\n records = [\n record\n for record in load_jsonl(dataset_path)\n if record.task in {\"apoptosis_event_replay\", \"replace_cell_without_global_retrain\"}\n ]\n pre_registry = CellRegistry.from_json(pre_registry_path)\n post_registry = CellRegistry.from_json(post_registry_path)\n pre_router = build_router(router_name, pre_registry, top_k=top_k)\n post_router = build_router(router_name, post_registry, top_k=top_k)\n\n transitions = []\n for record in records:\n pre_decision = pre_router.route(record)\n post_decision = post_router.route(record)\n transitions.append(\n {\n \"record_id\": record.record_id,\n \"domain_path\": record.domain_path,\n \"stale_cell_id\": record.stale_cell_id,\n \"expected_cell_id\": record.expected_cell_id,\n \"pre_selected_cell_id\": pre_decision.selected_cell_id,\n \"post_selected_cell_id\": post_decision.selected_cell_id,\n \"changed\": pre_decision.selected_cell_id != post_decision.selected_cell_id,\n \"post_matches_expected\": post_decision.selected_cell_id == record.expected_cell_id,\n \"pre_candidates\": pre_decision.candidates,\n \"post_candidates\": post_decision.candidates,\n }\n )\n\n changed = [item for item in transitions if item[\"changed\"]]\n post_matches = [item for item in transitions if item[\"post_matches_expected\"]]\n return {\n \"simulation\": \"registry_transition\",\n \"dataset\": str(dataset_path),\n \"pre_registry\": str(pre_registry_path),\n \"post_registry\": str(post_registry_path),\n \"router\": router_name,\n \"record_count\": len(transitions),\n \"changed_count\": len(changed),\n \"post_match_rate\": len(post_matches) / len(transitions) if transitions else 0.0,\n \"transitions\": transitions,\n }","instruction":"Explain the role of `def simulate_registry_transition(dataset_path: str | Path, pre_registry_path: str | Path, post_registry_path: str | Path, router_name: str='keyword', top_k: int=5) -> dict[str, Any]` in Primitive Foundry.","output":"`simulate_registry_transition` is a function in `primitive_foundry.lifecycle`. It belongs to the dataset, router area of Primitive Foundry.","source_id":"primitive_foundry.lifecycle.simulate_registry_transition","task":"python_symbol_explanation"} {"id":"primitive_foundry.marketplace_channels.build_marketplace_channel_plan::explain","input":"Module: primitive_foundry.marketplace_channels\nDomains: release, marketplace, commercial, dataset, benchmark\nSource path: primitive_foundry/marketplace_channels.py\n\ndef build_marketplace_channel_plan(\n *,\n listing: dict[str, Any],\n marketplace_metadata: dict[str, Any],\n build_context: BuildContext = DEFAULT_BUILD_CONTEXT,\n) -> dict[str, Any]:\n target_size = str(listing.get(\"target_size\") or \"\")\n family = str(listing.get(\"family\") or \"\")\n canonical = canonical_family(family)\n family_category = FAMILY_REGISTRY.get(canonical).category if canonical in FAMILY_REGISTRY else \"\"\n selected = []\n for profile in CHANNEL_PROFILES:\n include = target_size in profile[\"best_for\"] or profile[\"rank\"] <= 3\n if family_category in {\"evaluation\", \"benchmark\"} and profile[\"channel_id\"] == \"huggingface_hub\":\n include = True\n if include:\n selected.append(profile)\n plan = {\n \"manifest_type\": \"aml_marketplace_channel_plan\",\n \"created_at\": build_context.now(),\n \"release_id\": listing.get(\"release_id\"),\n \"sku\": listing.get(\"sku\"),\n \"family\": family,\n \"target_size\": target_size,\n \"market_regions\": listing.get(\"market_regions\", []),\n \"primary_channel\": \"aws_data_exchange\",\n \"secondary_channels\": [\"snowflake_marketplace\", \"databricks_marketplace\"],\n \"community_funnel\": \"huggingface_hub\",\n \"external_upload_allowed\": False,\n \"private_local_only_until_approved\": True,\n \"patent_sensitive\": True,\n \"ranking_basis\": [\n \"paid enterprise data-product buyer access\",\n \"private offer or gated access support\",\n \"fit for dataset/eval/benchmark artifacts\",\n \"US and Europe commercial path\",\n \"ability to preserve local-private release gate until approval\",\n ],\n \"selected_channels\": selected,\n \"source_urls\": MARKETPLACE_SOURCE_URLS,\n \"local_package_requirements\": [\n \"MARKETPLACE_LISTING.json\",\n \"MARKETPLACE_METADATA.json\",\n \"COMMERCIAL_READINESS.json\",\n \"TERMS.md\",\n \"LEGAL_REVIEW_PACKET.json\",\n \"BUYER_SAMPLE_POLICY.json\",\n \"VERSION_POLICY.json\",\n \"PRICING_EVIDENCE.json\",\n \"bundle/README.md\",\n \"bundle/DATASET_CARD.md\",\n \"bundle/SCHEMA.json\",\n \"bundle/QUALITY_REPORT.md\",\n \"bundle/PROVENANCE_MANIFEST.json\",\n \"bundle/CHECKSUMS.sha256\",\n ],\n \"marketplace_metadata_hash\": marketplace_metadata.get(\"metadata_hash\"),\n }\n plan[\"channel_plan_hash\"] = sha256_json({**plan, \"channel_plan_hash\": \"\"})\n return plan","instruction":"Explain the role of `def build_marketplace_channel_plan(*, listing: dict[str, Any], marketplace_metadata: dict[str, Any], build_context: BuildContext=DEFAULT_BUILD_CONTEXT) -> dict[str, Any]` in Primitive Foundry.","output":"`build_marketplace_channel_plan` is a function in `primitive_foundry.marketplace_channels`. It belongs to the release, marketplace, commercial, dataset, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.marketplace_channels.build_marketplace_channel_plan","task":"python_symbol_explanation"} {"id":"primitive_foundry.marketplace_channels.write_marketplace_channel_plan::explain","input":"Module: primitive_foundry.marketplace_channels\nDomains: release, marketplace\nSource path: primitive_foundry/marketplace_channels.py\n\ndef write_marketplace_channel_plan(\n *,\n release_dir: str | Path,\n listing: dict[str, Any],\n marketplace_metadata: dict[str, Any],\n build_context: BuildContext = DEFAULT_BUILD_CONTEXT,\n) -> dict[str, Any]:\n directory = Path(release_dir)\n plan = build_marketplace_channel_plan(\n listing=listing,\n marketplace_metadata=marketplace_metadata,\n build_context=build_context,\n )\n path = directory / \"MARKETPLACE_CHANNEL_PLAN.json\"\n path.write_text(json.dumps(plan, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return {\"path\": str(path), \"payload\": plan}","instruction":"Explain the role of `def write_marketplace_channel_plan(*, release_dir: str | Path, listing: dict[str, Any], marketplace_metadata: dict[str, Any], build_context: BuildContext=DEFAULT_BUILD_CONTEXT) -> dict[str, Any]` in Primitive Foundry.","output":"`write_marketplace_channel_plan` is a function in `primitive_foundry.marketplace_channels`. It belongs to the release, marketplace area of Primitive Foundry.","source_id":"primitive_foundry.marketplace_channels.write_marketplace_channel_plan","task":"python_symbol_explanation"} {"id":"primitive_foundry.marketplace_channels.verify_marketplace_channel_plan_payload::explain","input":"Module: primitive_foundry.marketplace_channels\nDomains: release, marketplace\nSource path: primitive_foundry/marketplace_channels.py\n\ndef verify_marketplace_channel_plan_payload(payload: dict[str, Any], listing: dict[str, Any]) -> list[str]:\n failures = []\n if payload.get(\"manifest_type\") != \"aml_marketplace_channel_plan\":\n failures.append(\"invalid_channel_plan_type\")\n if payload.get(\"channel_plan_hash\") != sha256_json({**payload, \"channel_plan_hash\": \"\"}):\n failures.append(\"channel_plan_hash_mismatch\")\n if payload.get(\"release_id\") != listing.get(\"release_id\"):\n failures.append(\"channel_plan_release_id_mismatch\")\n if payload.get(\"sku\") != listing.get(\"sku\"):\n failures.append(\"channel_plan_sku_mismatch\")\n if payload.get(\"primary_channel\") != \"aws_data_exchange\":\n failures.append(\"channel_plan_primary_not_aws_data_exchange\")\n selected_ids = [item.get(\"channel_id\") for item in payload.get(\"selected_channels\", [])]\n for channel_id in (\"aws_data_exchange\", \"snowflake_marketplace\", \"databricks_marketplace\"):\n if channel_id not in selected_ids:\n failures.append(f\"channel_plan_missing:{channel_id}\")\n if payload.get(\"external_upload_allowed\") is not False:\n failures.append(\"channel_plan_allows_external_upload\")\n if payload.get(\"private_local_only_until_approved\") is not True:\n failures.append(\"channel_plan_not_private_local\")\n if set(payload.get(\"market_regions\", [])) != {\"US\", \"EU\"}:\n failures.append(\"channel_plan_regions_not_us_eu\")\n if payload.get(\"patent_sensitive\") is not True:\n failures.append(\"channel_plan_not_patent_sensitive\")\n required_sources = set(MARKETPLACE_SOURCE_URLS)\n if not required_sources.issubset(set((payload.get(\"source_urls\") or {}).keys())):\n failures.append(\"channel_plan_missing_source_urls\")\n return failures","instruction":"Explain the role of `def verify_marketplace_channel_plan_payload(payload: dict[str, Any], listing: dict[str, Any]) -> list[str]` in Primitive Foundry.","output":"`verify_marketplace_channel_plan_payload` is a function in `primitive_foundry.marketplace_channels`. It belongs to the release, marketplace area of Primitive Foundry.","source_id":"primitive_foundry.marketplace_channels.verify_marketplace_channel_plan_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.marketplace_channels.verify_marketplace_channel_plan::explain","input":"Module: primitive_foundry.marketplace_channels\nDomains: marketplace\nSource path: primitive_foundry/marketplace_channels.py\n\ndef verify_marketplace_channel_plan(path: str | Path, listing: dict[str, Any]) -> dict[str, Any]:\n plan_path = Path(path)\n if not plan_path.exists():\n return {\"passed\": False, \"path\": str(plan_path), \"failures\": [\"missing_channel_plan\"]}\n payload = json.loads(plan_path.read_text(encoding=\"utf-8\"))\n failures = verify_marketplace_channel_plan_payload(payload, listing)\n return {\n \"passed\": not failures,\n \"path\": str(plan_path),\n \"primary_channel\": payload.get(\"primary_channel\"),\n \"selected_channels\": [item.get(\"channel_id\") for item in payload.get(\"selected_channels\", [])],\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_marketplace_channel_plan(path: str | Path, listing: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_marketplace_channel_plan` is a function in `primitive_foundry.marketplace_channels`. It belongs to the marketplace area of Primitive Foundry.","source_id":"primitive_foundry.marketplace_channels.verify_marketplace_channel_plan","task":"python_symbol_explanation"} {"id":"primitive_foundry.marketplace_packet.write_marketplace_packets::explain","input":"Module: primitive_foundry.marketplace_packet\nDomains: release, marketplace, commercial\nSource path: primitive_foundry/marketplace_packet.py\n\ndef write_marketplace_packets(\n *,\n release_dir: str | Path,\n output_dir: str | Path | None = None,\n) -> dict[str, Any]:\n directory = Path(release_dir)\n if not directory.exists():\n raise FileNotFoundError(f\"release_dir does not exist: {directory}\")\n out = Path(output_dir) if output_dir else directory / \"marketplace_packets\"\n out.mkdir(parents=True, exist_ok=True)\n\n listing = read_json(directory / \"MARKETPLACE_LISTING.json\")\n metadata = read_json(directory / \"MARKETPLACE_METADATA.json\")\n channel_plan = read_json(directory / \"MARKETPLACE_CHANNEL_PLAN.json\")\n readiness = read_json(directory / \"COMMERCIAL_READINESS.json\")\n legal = read_json(directory / \"LEGAL_REVIEW_PACKET.json\")\n sample_policy = read_json(directory / \"BUYER_SAMPLE_POLICY.json\")\n pricing = read_json(directory / \"PRICING_EVIDENCE.json\")\n commercial = verify_commercial_release(directory)\n external = verify_external_listing_release(directory)\n\n context = {\n \"release_dir\": str(directory),\n \"packet_dir\": str(out),\n \"listing\": listing,\n \"metadata\": metadata,\n \"channel_plan\": channel_plan,\n \"readiness\": readiness,\n \"legal\": legal,\n \"sample_policy\": sample_policy,\n \"pricing\": pricing,\n \"commercial\": commercial,\n \"external\": external,\n }\n files = {\n \"PRE_ACCOUNT_READINESS.json\": json.dumps(build_readiness_payload(context), indent=2, sort_keys=True) + \"\\n\",\n \"PRE_ACCOUNT_READINESS.md\": render_readiness_markdown(context),\n \"ACCOUNT_FIELDS_TEMPLATE.json\": json.dumps(ACCOUNT_FIELDS_TEMPLATE, indent=2, sort_keys=True) + \"\\n\",\n \"aws_data_exchange_listing_draft.md\": render_channel_draft(\"AWS Data Exchange\", context),\n \"snowflake_marketplace_listing_draft.md\": render_channel_draft(\"Snowflake Marketplace\", context),\n \"databricks_marketplace_listing_draft.md\": render_channel_draft(\"Databricks Marketplace\", context),\n \"huggingface_gated_preview_draft.md\": render_channel_draft(\"Hugging Face gated preview\", context),\n }\n written = []\n for name, content in files.items():\n path = out / name\n path.write_text(content, encoding=\"utf-8\")\n written.append(str(path))\n\n manifest = {\n \"manifest_type\": \"aml_marketplace_packet_manifest\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"release_id\": listing.get(\"release_id\"),\n \"sku\": listing.get(\"sku\"),\n \"packet_dir\": str(out),\n \"commercial_passed\": bool(commercial.get(\"passed\")),\n \"external_listing_passed\": bool(external.get(\"passed\")),\n \"external_blockers\": external.get(\"failures\", []),\n \"files\": written,\n }\n manifest[\"packet_manifest_hash\"] = sha256_json({**manifest, \"packet_manifest_hash\": \"\"})\n manifest_path = out / \"MARKETPLACE_PACKET_MANIFEST.json\"\n manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n written.append(str(manifest_path))\n return {\n \"passed\": bool(commercial.get(\"passed\")) and all(Path(path).exists() for path in written),\n \"release_id\": listing.get(\"release_id\"),\n \"sku\": listing.get(\"sku\"),\n \"packet_dir\": str(out),\n \"commercial_passed\": bool(commercial.get(\"passed\")),\n \"external_listing_passed\": bool(external.get(\"passed\")),\n \"external_blockers\": external.get(\"failures\", []),\n \"files\": written,\n \"manifest\": str(manifest_path),\n }","instruction":"Explain the role of `def write_marketplace_packets(*, release_dir: str | Path, output_dir: str | Path | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`write_marketplace_packets` is a function in `primitive_foundry.marketplace_packet`. It belongs to the release, marketplace, commercial area of Primitive Foundry.","source_id":"primitive_foundry.marketplace_packet.write_marketplace_packets","task":"python_symbol_explanation"} {"id":"primitive_foundry.marketplace_packet.read_json::explain","input":"Module: primitive_foundry.marketplace_packet\nDomains: release, marketplace\nSource path: primitive_foundry/marketplace_packet.py\n\ndef read_json(path: Path) -> dict[str, Any]:\n if not path.exists():\n raise FileNotFoundError(f\"required release artifact missing: {path}\")\n return json.loads(path.read_text(encoding=\"utf-8\"))","instruction":"Explain the role of `def read_json(path: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`read_json` is a function in `primitive_foundry.marketplace_packet`. It belongs to the release, marketplace area of Primitive Foundry.","source_id":"primitive_foundry.marketplace_packet.read_json","task":"python_symbol_explanation"} {"id":"primitive_foundry.marketplace_packet.build_readiness_payload::explain","input":"Module: primitive_foundry.marketplace_packet\nDomains: release, marketplace, commercial\nSource path: primitive_foundry/marketplace_packet.py\n\ndef build_readiness_payload(context: dict[str, Any]) -> dict[str, Any]:\n listing = context[\"listing\"]\n metadata = context[\"metadata\"]\n external = context[\"external\"]\n payload = {\n \"manifest_type\": \"aml_pre_account_marketplace_readiness\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"release_id\": listing.get(\"release_id\"),\n \"sku\": listing.get(\"sku\"),\n \"title\": listing.get(\"title\"),\n \"price_usd\": listing.get(\"price_usd\"),\n \"target_size\": listing.get(\"target_size\"),\n \"record_count\": listing.get(\"record_count\"),\n \"market_regions\": listing.get(\"market_regions\", []),\n \"primary_marketplace\": metadata.get(\"primary_marketplace\"),\n \"secondary_marketplaces\": metadata.get(\"secondary_marketplaces\", []),\n \"community_funnel\": metadata.get(\"community_funnel\"),\n \"commercial_passed\": bool(context[\"commercial\"].get(\"passed\")),\n \"external_listing_passed\": bool(external.get(\"passed\")),\n \"external_blockers\": external.get(\"failures\", []),\n \"account_fields_needed\": [\n \"seller/provider account for AWS Data Exchange\",\n \"provider account for Snowflake Marketplace\",\n \"provider account for Databricks Marketplace\",\n \"private or gated organization space on Hugging Face, only after approval\",\n \"support contact\",\n \"refund policy\",\n \"tax/VAT account status\",\n \"legal reviewer and reviewed_at approval\",\n ],\n \"external_upload_allowed_now\": False,\n }\n payload[\"readiness_hash\"] = sha256_json({**payload, \"readiness_hash\": \"\"})\n return payload","instruction":"Explain the role of `def build_readiness_payload(context: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`build_readiness_payload` is a function in `primitive_foundry.marketplace_packet`. It belongs to the release, marketplace, commercial area of Primitive Foundry.","source_id":"primitive_foundry.marketplace_packet.build_readiness_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.marketplace_packet.render_readiness_markdown::explain","input":"Module: primitive_foundry.marketplace_packet\nDomains: privacy, release, marketplace\nSource path: primitive_foundry/marketplace_packet.py\n\ndef render_readiness_markdown(context: dict[str, Any]) -> str:\n listing = context[\"listing\"]\n metadata = context[\"metadata\"]\n external = context[\"external\"]\n blockers = \"\\n\".join(f\"- `{item}`\" for item in external.get(\"failures\", [])) or \"- none\"\n return (\n f\"# Pre-Account Readiness: {listing.get('release_id')}\\n\\n\"\n \"This packet is local and private. Do not upload it externally until \"\n \"`verify-external-listing` passes.\\n\\n\"\n f\"- SKU: `{listing.get('sku')}`\\n\"\n f\"- Title: {listing.get('title')}\\n\"\n f\"- Price: ${listing.get('price_usd')} {listing.get('currency', 'USD')}\\n\"\n f\"- Records: {listing.get('record_count')} ({listing.get('target_size')})\\n\"\n f\"- Regions: {', '.join(listing.get('market_regions', []))}\\n\"\n f\"- Primary marketplace: `{metadata.get('primary_marketplace')}`\\n\"\n f\"- Secondary marketplaces: {', '.join(metadata.get('secondary_marketplaces', []))}\\n\"\n f\"- Community funnel: `{metadata.get('community_funnel')}`\\n\\n\"\n \"## Current External Listing Blockers\\n\\n\"\n f\"{blockers}\\n\\n\"\n \"## Fill After Accounts Exist\\n\\n\"\n \"- `support_contact`\\n\"\n \"- `refund_policy`\\n\"\n \"- `tax_vat_status`\\n\"\n \"- legal reviewer, notes, and review timestamp through `approve-external-listing`\\n\\n\"\n \"## Approval Command Shape\\n\\n\"\n \"```bash\\n\"\n \"primitive-foundry approve-external-listing \\\\\\n\"\n f\" --release-dir {context['release_dir']} \\\\\\n\"\n \" --reviewer \\\"qualified-reviewer-name\\\" \\\\\\n\"\n \" --notes \\\"Reviewed package contents, privacy posture, marketplace claims, terms, and account fields.\\\" \\\\\\n\"\n \" --support-contact \\\"[REDACTED_EMAIL]\\\" \\\\\\n\"\n \" --refund-policy \\\"Refund requests are reviewed within 14 days for undelivered, corrupt, or materially misdescribed packages.\\\" \\\\\\n\"\n \" --tax-vat-status \\\"Seller account configured for US and EU tax/VAT review.\\\"\\n\"\n \"```\\n\"\n )","instruction":"Explain the role of `def render_readiness_markdown(context: dict[str, Any]) -> str` in Primitive Foundry.","output":"`render_readiness_markdown` is a function in `primitive_foundry.marketplace_packet`. It belongs to the privacy, release, marketplace area of Primitive Foundry.","source_id":"primitive_foundry.marketplace_packet.render_readiness_markdown","task":"python_symbol_explanation"} {"id":"primitive_foundry.marketplace_packet.channel_profile::explain","input":"Module: primitive_foundry.marketplace_packet\nDomains: marketplace, license, dataset\nSource path: primitive_foundry/marketplace_packet.py\n\ndef channel_profile(channel_plan: dict[str, Any], channel_name: str) -> dict[str, Any]:\n normalized = channel_name.lower().replace(\" \", \"_\").replace(\"gated_preview\", \"hub\")\n aliases = {\n \"aws_data_exchange\": \"aws_data_exchange\",\n \"snowflake_marketplace\": \"snowflake_marketplace\",\n \"databricks_marketplace\": \"databricks_marketplace\",\n \"hugging_face_hub\": \"huggingface_hub\",\n }\n channel_id = aliases.get(normalized, normalized)\n for profile in channel_plan.get(\"selected_channels\", []):\n if profile.get(\"channel_id\") == channel_id:\n return profile\n if channel_plan.get(\"community_funnel\") == channel_id:\n return {\n \"channel_id\": channel_id,\n \"required_before_external_listing\": [\n \"public_dataset_card_review\",\n \"gated_access_policy\",\n \"no_public_record_sample\",\n \"contact_capture_fields\",\n \"license_card\",\n ],\n }\n return {\"channel_id\": channel_id, \"required_before_external_listing\": []}","instruction":"Explain the role of `def channel_profile(channel_plan: dict[str, Any], channel_name: str) -> dict[str, Any]` in Primitive Foundry.","output":"`channel_profile` is a function in `primitive_foundry.marketplace_packet`. It belongs to the marketplace, license, dataset area of Primitive Foundry.","source_id":"primitive_foundry.marketplace_packet.channel_profile","task":"python_symbol_explanation"} {"id":"primitive_foundry.migrations.__init__.upgrade_record::explain","input":"Module: primitive_foundry.migrations.__init__\nDomains: foundry\nSource path: primitive_foundry/migrations/__init__.py\n\ndef upgrade_record(record: dict[str, Any]) -> dict[str, Any]:\n upgraded = upgrade_v0_4_to_v0_5(dict(record))\n upgraded = upgrade_v0_5_to_v1_0(upgraded)\n return upgraded","instruction":"Explain the role of `def upgrade_record(record: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`upgrade_record` is a function in `primitive_foundry.migrations.__init__`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.migrations.__init__.upgrade_record","task":"python_symbol_explanation"} {"id":"primitive_foundry.migrations.v0_4_to_v0_5.upgrade::explain","input":"Module: primitive_foundry.migrations.v0_4_to_v0_5\nDomains: dataset\nSource path: primitive_foundry/migrations/v0_4_to_v0_5.py\n\ndef upgrade(record: dict[str, Any]) -> dict[str, Any]:\n metadata = dict(record.get(\"metadata\") or {})\n metadata.setdefault(\"dataset_version\", record.get(\"dataset_version\", \"0.5.0\"))\n record[\"metadata\"] = metadata\n record.setdefault(\"expected_cell_ids\", [record.get(\"expected_cell_id\")])\n return record","instruction":"Explain the role of `def upgrade(record: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`upgrade` is a function in `primitive_foundry.migrations.v0_4_to_v0_5`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.migrations.v0_4_to_v0_5.upgrade","task":"python_symbol_explanation"} {"id":"primitive_foundry.migrations.v0_5_to_v1_0.upgrade::explain","input":"Module: primitive_foundry.migrations.v0_5_to_v1_0\nDomains: dataset\nSource path: primitive_foundry/migrations/v0_5_to_v1_0.py\n\ndef upgrade(record: dict[str, Any]) -> dict[str, Any]:\n metadata = dict(record.get(\"metadata\") or {})\n rubric = record.get(\"rubric\") or metadata.get(\"rubric\") or {}\n buyer_task = record.get(\"buyer_task\") or metadata.get(\"buyer_task\") or {}\n rubric = rubric if isinstance(rubric, dict) else {}\n buyer_task = buyer_task if isinstance(buyer_task, dict) else {}\n record.setdefault(\n \"rubric_id\",\n rubric.get(\"rubric_id\")\n or rubric.get(\"id\")\n or buyer_task.get(\"rubric_id\")\n or metadata.get(\"rubric_id\")\n or \"route_and_provenance\",\n )\n record.setdefault(\"domain_review\", metadata.get(\"domain_review\") or {})\n record.setdefault(\"family_fields\", metadata.get(\"family_metadata\") or metadata.get(\"metadata\") or {})\n metadata.setdefault(\"dataset_version\", \"1.0.0\")\n record[\"metadata\"] = metadata\n return record","instruction":"Explain the role of `def upgrade(record: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`upgrade` is a function in `primitive_foundry.migrations.v0_5_to_v1_0`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.migrations.v0_5_to_v1_0.upgrade","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.append_inbox_event::explain","input":"Module: primitive_foundry.node_ops\nDomains: foundry\nSource path: primitive_foundry/node_ops.py\n\ndef append_inbox_event(\n *,\n inbox: str | Path,\n text: str,\n source_path: str | Path,\n event_id: str | None = None,\n tags: list[str] | None = None,\n source_id: str | None = None,\n metadata: dict[str, Any] | None = None,\n) -> dict[str, Any]:\n source = Path(source_path).expanduser()\n if not source.exists():\n raise ValueError(f\"source_path does not exist: {source}\")\n if not text.strip():\n raise ValueError(\"text is required\")\n event = {\n \"event_id\": event_id or \"evt-\" + datetime.now(timezone.utc).strftime(\"%Y%m%d%H%M%S%f\"),\n \"text\": text.strip(),\n \"source_path\": str(source),\n \"source_id\": source_id,\n \"tags\": tags or [],\n \"metadata\": metadata or {},\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n }\n target = Path(inbox)\n target.parent.mkdir(parents=True, exist_ok=True)\n with target.open(\"a\", encoding=\"utf-8\") as handle:\n handle.write(json.dumps(event, sort_keys=True))\n handle.write(\"\\n\")\n return {\"inbox\": str(target), \"event\": event, \"event_hash\": sha256_json(event)}","instruction":"Explain the role of `def append_inbox_event(*, inbox: str | Path, text: str, source_path: str | Path, event_id: str | None=None, tags: list[str] | None=None, source_id: str | None=None, metadata: dict[str, Any] | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`append_inbox_event` is a function in `primitive_foundry.node_ops`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.append_inbox_event","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.validate_inbox::explain","input":"Module: primitive_foundry.node_ops\nDomains: foundry\nSource path: primitive_foundry/node_ops.py\n\ndef validate_inbox(inbox: str | Path) -> dict[str, Any]:\n rows = read_product_event_rows(inbox)\n invalid = [row for row in rows if row.event is None]\n duplicate_ids = sorted(\n event_id\n for event_id in {row.event.event_id for row in rows if row.event}\n if sum(1 for row in rows if row.event and row.event.event_id == event_id) > 1\n )\n missing_sources = sorted(\n {\n row.event.source_path\n for row in rows\n if row.event and not Path(row.event.source_path).expanduser().exists()\n }\n )\n failures = []\n if invalid:\n failures.append(\"invalid_events\")\n if duplicate_ids:\n failures.append(\"duplicate_event_ids\")\n if missing_sources:\n failures.append(\"missing_sources\")\n return {\n \"passed\": not failures,\n \"inbox\": str(inbox),\n \"event_count\": len([row for row in rows if row.event]),\n \"invalid_count\": len(invalid),\n \"duplicate_event_ids\": duplicate_ids,\n \"missing_sources\": missing_sources,\n \"failures\": failures,\n }","instruction":"Explain the role of `def validate_inbox(inbox: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`validate_inbox` is a function in `primitive_foundry.node_ops`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.validate_inbox","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.verify_product_catalog::explain","input":"Module: primitive_foundry.node_ops\nDomains: foundry\nSource path: primitive_foundry/node_ops.py\n\ndef verify_product_catalog(path: str | Path) -> dict[str, Any]:\n catalog_path = Path(path)\n if not catalog_path.exists():\n return {\"passed\": False, \"catalog\": str(catalog_path), \"failures\": [\"missing_catalog\"], \"product_count\": 0}\n catalog = json.loads(catalog_path.read_text(encoding=\"utf-8\"))\n failures = []\n if catalog.get(\"manifest_type\") != \"aml_product_catalog\":\n failures.append(\"invalid_manifest_type\")\n expected = sha256_json({**catalog, \"catalog_hash\": \"\"})\n if catalog.get(\"catalog_hash\") != expected:\n failures.append(\"catalog_hash_mismatch\")\n lock_failures = []\n for product in catalog.get(\"products\", []):\n lock_path = product.get(\"manifest_lock\")\n if not lock_path:\n lock_failures.append(\"missing_manifest_lock_path\")\n continue\n verified = verify_manifest_lock(lock_path)\n if not verified[\"passed\"]:\n lock_failures.append(f\"{lock_path}:{','.join(verified['failures'])}\")\n if lock_failures:\n failures.append(\"product_lock_failures\")\n return {\n \"passed\": not failures,\n \"catalog\": str(catalog_path),\n \"product_count\": len(catalog.get(\"products\", [])),\n \"lock_failures\": lock_failures,\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_product_catalog(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_product_catalog` is a function in `primitive_foundry.node_ops`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.verify_product_catalog","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.repair_product_manifest_lock::explain","input":"Module: primitive_foundry.node_ops\nDomains: foundry\nSource path: primitive_foundry/node_ops.py\n\ndef repair_product_manifest_lock(candidate_dir: str | Path) -> dict[str, Any]:\n candidate = Path(candidate_dir)\n lock_path = candidate / \"MANIFEST.lock\"\n if not lock_path.exists():\n raise ValueError(f\"Missing product manifest lock: {lock_path}\")\n lock = json.loads(lock_path.read_text(encoding=\"utf-8\"))\n artifacts = lock.get(\"artifacts\", {})\n if not artifacts:\n raise ValueError(\"Manifest lock has no artifacts to repair.\")\n repaired = write_manifest_lock(lock_path, {**lock, \"hashes\": artifact_hashes(artifacts)})\n verified = verify_manifest_lock(lock_path)\n return {\n \"repaired\": verified[\"passed\"],\n \"candidate_dir\": str(candidate),\n \"manifest_lock\": str(lock_path),\n \"candidate_id\": repaired.get(\"candidate_id\"),\n \"verify\": verified,\n }","instruction":"Explain the role of `def repair_product_manifest_lock(candidate_dir: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`repair_product_manifest_lock` is a function in `primitive_foundry.node_ops`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.repair_product_manifest_lock","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.node_health::explain","input":"Module: primitive_foundry.node_ops\nDomains: release\nSource path: primitive_foundry/node_ops.py\n\ndef node_health(\n *,\n output_root: str | Path = \"products\",\n state_path: str | Path | None = None,\n inbox: str | Path | None = None,\n run_audit: bool = False,\n work_dir: str | Path = \".\",\n require_policy: bool = True,\n) -> dict[str, Any]:\n root = Path(output_root)\n state = verify_stream_state(state_path or root / \"STREAM_STATE.json\")\n catalog = verify_product_catalog(root / \"PRODUCT_CATALOG.json\")\n release_index_path = root / \"RELEASE_INDEX.json\"\n release_index = (\n verify_release_index(release_index_path)\n if release_index_path.exists()\n else {\"passed\": False, \"index\": str(release_index_path), \"failures\": [\"missing_release_index\"]}\n )\n inbox_result = validate_inbox(inbox) if inbox else {\"passed\": True, \"event_count\": None, \"failures\": []}\n rejected_result = validate_rejected_log(root / \"REJECTED_EVENTS.jsonl\")\n policy_path = root / \"PRIVATE_RELEASE_POLICY.json\"\n policy = (\n verify_release_policy(policy_path)\n if policy_path.exists()\n else {\n \"passed\": not require_policy,\n \"policy\": str(policy_path),\n \"skipped\": not require_policy,\n \"failures\": [\"missing_release_policy\"] if require_policy else [],\n }\n )\n audit = {\"passed\": True, \"skipped\": True}\n if run_audit:\n from .audit import audit_local_paths\n\n audit = audit_local_paths(work_dir)\n checks = {\n \"stream_state\": state,\n \"product_catalog\": catalog,\n \"release_index\": release_index,\n \"inbox\": inbox_result,\n \"rejected_log\": rejected_result,\n \"release_policy\": policy,\n \"audit\": audit,\n }\n return {\n \"passed\": all(item.get(\"passed\", False) for item in checks.values()),\n \"output_root\": str(root),\n \"checks\": checks,\n }","instruction":"Explain the role of `def node_health(*, output_root: str | Path='products', state_path: str | Path | None=None, inbox: str | Path | None=None, run_audit: bool=False, work_dir: str | Path='.', require_policy: bool=True) -> dict[str, Any]` in Primitive Foundry.","output":"`node_health` is a function in `primitive_foundry.node_ops`. It belongs to the release area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.node_health","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.package_product::explain","input":"Module: primitive_foundry.node_ops\nDomains: marketplace, commercial, dataset, compliance\nSource path: primitive_foundry/node_ops.py\n\ndef package_product(\n *,\n candidate_dir: str | Path,\n output_dir: str | Path = \"packages\",\n) -> dict[str, Any]:\n candidate = Path(candidate_dir)\n lock_path = candidate / \"MANIFEST.lock\"\n if not verify_manifest_lock(lock_path)[\"passed\"]:\n raise ValueError(f\"Cannot package product with invalid lock: {lock_path}\")\n lock = json.loads(lock_path.read_text(encoding=\"utf-8\"))\n candidate_id = str(lock[\"candidate_id\"])\n target_dir = Path(output_dir)\n target_dir.mkdir(parents=True, exist_ok=True)\n package_path = target_dir / f\"{candidate_id}.tar.gz\"\n package_tmp_path = target_dir / f\".{candidate_id}.{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S%f')}.tar.gz.tmp\"\n artifacts = lock.get(\"artifacts\", {})\n include_paths = [\n artifacts.get(\"bundle_dir\"),\n artifacts.get(\"report_card\"),\n str(lock_path),\n artifacts.get(\"promotion\"),\n artifacts.get(\"review\"),\n ]\n for commercial_name in (\n \"MARKETPLACE_LISTING.json\",\n \"COMMERCIAL_READINESS.json\",\n \"TERMS.md\",\n \"MARKETPLACE_METADATA.json\",\n \"MARKETPLACE_CHANNEL_PLAN.json\",\n \"BUYER_SAMPLE_POLICY.json\",\n \"VERSION_POLICY.json\",\n \"PRICING_EVIDENCE.json\",\n \"LEGAL_REVIEW_PACKET.json\",\n \"CROISSANT.jsonld\",\n \"SCHEMA_ORG_DATASET.jsonld\",\n \"DCAT.jsonld\",\n \"FTC_CLAIMS_MATRIX.json\",\n \"COMPLIANCE_MATRIX.json\",\n \"DATASHEET.md\",\n ):\n commercial_path = candidate / commercial_name\n if commercial_path.exists():\n include_paths.append(str(commercial_path))\n delivery_dir = candidate / \"delivery\"\n if delivery_dir.exists():\n include_paths.append(str(delivery_dir))\n aws_dir = candidate / \"aws_data_exchange\"\n if aws_dir.exists():\n include_paths.append(str(aws_dir))\n try:\n archive_entries = []\n for value in include_paths:\n if not value:\n continue\n path = Path(value)\n if not path.exists():\n raise ValueError(f\"Package artifact missing: {path}\")\n ensure_no_package_symlinks(path)\n archive_entries.append((path, str(Path(candidate_id) / path.name)))\n write_deterministic_tar_gz(package_tmp_path, archive_entries)\n package_hash = sha256_bytes(package_tmp_path.read_bytes())\n package_tmp_path.replace(package_path)\n finally:\n if package_tmp_path.exists():\n package_tmp_path.unlink()\n manifest = {\n \"manifest_type\": \"aml_product_package\",\n \"candidate_id\": candidate_id,\n \"package\": str(package_path),\n \"package_hash\": package_hash,\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"raw_sources_included\": False,\n \"included\": [str(value) for value in include_paths if value],\n }\n manifest[\"package_manifest_hash\"] = sha256_json({**manifest, \"package_manifest_hash\": \"\"})\n manifest_path = target_dir / f\"{candidate_id}.package.json\"\n manifest_tmp_path = target_dir / f\".{candidate_id}.{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S%f')}.package.json.tmp\"\n manifest_tmp_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n manifest_tmp_path.replace(manifest_path)\n return {**manifest, \"manifest\": str(manifest_path)}","instruction":"Explain the role of `def package_product(*, candidate_dir: str | Path, output_dir: str | Path='packages') -> dict[str, Any]` in Primitive Foundry.","output":"`package_product` is a function in `primitive_foundry.node_ops`. It belongs to the marketplace, commercial, dataset, compliance area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.package_product","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.verify_package::explain","input":"Module: primitive_foundry.node_ops\nDomains: sterilization, release, marketplace, commercial, dataset, compliance, source_card\nSource path: primitive_foundry/node_ops.py\n\ndef verify_package(manifest_path: str | Path) -> dict[str, Any]:\n manifest_file = Path(manifest_path)\n manifest = json.loads(manifest_file.read_text(encoding=\"utf-8\"))\n failures = []\n expected_manifest_hash = sha256_json({**manifest, \"package_manifest_hash\": \"\"})\n if manifest.get(\"manifest_type\") != \"aml_product_package\":\n failures.append(\"invalid_manifest_type\")\n if manifest.get(\"package_manifest_hash\") != expected_manifest_hash:\n failures.append(\"package_manifest_hash_mismatch\")\n candidate_id = str(manifest.get(\"candidate_id\") or \"\")\n if not candidate_id:\n failures.append(\"missing_candidate_id\")\n package_path = Path(manifest.get(\"package\", \"\"))\n if candidate_id and package_path.name != f\"{candidate_id}.tar.gz\":\n failures.append(\"package_name_candidate_mismatch\")\n if not package_path.exists():\n failures.append(\"missing_package\")\n members = []\n else:\n if sha256_bytes(package_path.read_bytes()) != manifest.get(\"package_hash\"):\n failures.append(\"package_hash_mismatch\")\n try:\n with tarfile.open(package_path, \"r:gz\") as archive:\n member_infos = archive.getmembers()\n members = [member.name for member in member_infos]\n failures.extend(verify_package_member_paths(member_infos, candidate_id))\n required_names = (\"bundle/README.md\", \"REPORT_CARD.md\", \"MANIFEST.lock\", \".promotion.json\", \".review.json\")\n for required in required_names:\n if not any(name.endswith(required) for name in members):\n failures.append(f\"missing_member:{required}\")\n embedded_lock_failures = verify_embedded_manifest_lock(archive, members, candidate_id)\n failures.extend(embedded_lock_failures)\n commercial_names = (\n \"MARKETPLACE_LISTING.json\",\n \"COMMERCIAL_READINESS.json\",\n \"TERMS.md\",\n \"MARKETPLACE_METADATA.json\",\n \"MARKETPLACE_CHANNEL_PLAN.json\",\n \"BUYER_SAMPLE_POLICY.json\",\n \"VERSION_POLICY.json\",\n \"PRICING_EVIDENCE.json\",\n \"LEGAL_REVIEW_PACKET.json\",\n \"CROISSANT.jsonld\",\n \"SCHEMA_ORG_DATASET.jsonld\",\n \"DCAT.jsonld\",\n \"COMPLIANCE_MATRIX.json\",\n \"DATASHEET.md\",\n )\n if any(any(name.endswith(commercial_name) for name in members) for commercial_name in commercial_names):\n for commercial_name in commercial_names:\n if not any(name.endswith(commercial_name) for name in members):\n failures.append(f\"missing_member:{commercial_name}\")\n forbidden = (\"source_cards.jsonl\", \"dataset.jsonl\", \"AUTONOMOUS_RELEASE.json\")\n for forbidden_name in forbidden:\n if any(name.endswith(forbidden_name) for name in members):\n failures.append(f\"raw_source_artifact_included:{forbidden_name}\")\n failures.extend(verify_package_sterilization(archive, members))\n except tarfile.TarError as exc:\n failures.append(f\"package_archive_unreadable:{exc}\")\n members = []\n if manifest.get(\"raw_sources_included\") is not False:\n failures.append(\"raw_sources_flag_not_false\")\n return {\n \"passed\": not failures,\n \"manifest\": str(manifest_file),\n \"package\": str(manifest.get(\"package\")),\n \"candidate_id\": candidate_id,\n \"member_count\": len(members),\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_package(manifest_path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_package` is a function in `primitive_foundry.node_ops`. It belongs to the sterilization, release, marketplace, commercial, dataset, compliance, source_card area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.verify_package","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.ensure_no_package_symlinks::explain","input":"Module: primitive_foundry.node_ops\nDomains: foundry\nSource path: primitive_foundry/node_ops.py\n\ndef ensure_no_package_symlinks(path: Path) -> None:\n if path.is_symlink():\n raise ValueError(f\"Package artifact may not be a symlink: {path}\")\n if path.is_dir():\n for item in path.rglob(\"*\"):\n if item.is_symlink():\n raise ValueError(f\"Package artifact tree may not contain symlinks: {item}\")","instruction":"Explain the role of `def ensure_no_package_symlinks(path: Path) -> None` in Primitive Foundry.","output":"`ensure_no_package_symlinks` is a function in `primitive_foundry.node_ops`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.ensure_no_package_symlinks","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.verify_package_member_paths::explain","input":"Module: primitive_foundry.node_ops\nDomains: foundry\nSource path: primitive_foundry/node_ops.py\n\ndef verify_package_member_paths(members: list[tarfile.TarInfo], candidate_id: str) -> list[str]:\n failures = []\n if not members:\n failures.append(\"empty_package\")\n return failures\n prefixes: set[str] = set()\n for member in members:\n name = member.name\n path = PurePosixPath(name)\n parts = path.parts\n if name.startswith(\"/\") or not parts or \"..\" in parts:\n failures.append(f\"unsafe_member_path:{name}\")\n continue\n if member.issym() or member.islnk():\n failures.append(f\"unsafe_member_link:{name}\")\n if member.isdev() or member.isfifo():\n failures.append(f\"unsafe_member_special_file:{name}\")\n if not (member.isfile() or member.isdir()):\n failures.append(f\"unsupported_member_type:{name}\")\n prefixes.add(parts[0])\n if candidate_id and parts[0] != candidate_id:\n failures.append(f\"member_candidate_prefix_mismatch:{name}\")\n if candidate_id and prefixes != {candidate_id}:\n failures.append(\"package_top_level_candidate_mismatch\")\n return failures","instruction":"Explain the role of `def verify_package_member_paths(members: list[tarfile.TarInfo], candidate_id: str) -> list[str]` in Primitive Foundry.","output":"`verify_package_member_paths` is a function in `primitive_foundry.node_ops`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.verify_package_member_paths","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.write_release_policy::explain","input":"Module: primitive_foundry.node_ops\nDomains: release\nSource path: primitive_foundry/node_ops.py\n\ndef write_release_policy(path: str | Path = artifact_path(\"products\", \"node-stream-operational\", \"PRIVATE_RELEASE_POLICY.json\")) -> dict[str, Any]:\n policy_path = Path(path)\n policy = {\n \"manifest_type\": \"aml_private_release_policy\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"patent_sensitive\": True,\n \"external_upload_allowed\": False,\n \"raw_sources_may_leave_node\": False,\n \"allowed_local_consumers\": [\"primitive-foundry-node\", \"local-reviewer\"],\n \"review_required\": True,\n \"package_constraints\": {\n \"include_raw_sources\": False,\n \"require_manifest_lock\": True,\n \"require_promotion_review\": True,\n },\n }\n policy[\"policy_hash\"] = sha256_json({**policy, \"policy_hash\": \"\"})\n policy_path.parent.mkdir(parents=True, exist_ok=True)\n policy_path.write_text(json.dumps(policy, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return {**policy, \"path\": str(policy_path)}","instruction":"Explain the role of `def write_release_policy(path: str | Path=artifact_path('products', 'node-stream-operational', 'PRIVATE_RELEASE_POLICY.json')) -> dict[str, Any]` in Primitive Foundry.","output":"`write_release_policy` is a function in `primitive_foundry.node_ops`. It belongs to the release area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.write_release_policy","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.verify_release_policy::explain","input":"Module: primitive_foundry.node_ops\nDomains: release\nSource path: primitive_foundry/node_ops.py\n\ndef verify_release_policy(path: str | Path) -> dict[str, Any]:\n policy_path = Path(path)\n policy = json.loads(policy_path.read_text(encoding=\"utf-8\"))\n failures = []\n if policy.get(\"manifest_type\") != \"aml_private_release_policy\":\n failures.append(\"invalid_manifest_type\")\n if policy.get(\"policy_hash\") != sha256_json({**policy, \"policy_hash\": \"\"}):\n failures.append(\"policy_hash_mismatch\")\n if policy.get(\"external_upload_allowed\") is not False:\n failures.append(\"external_upload_allowed\")\n if policy.get(\"raw_sources_may_leave_node\") is not False:\n failures.append(\"raw_sources_may_leave_node\")\n if policy.get(\"review_required\") is not True:\n failures.append(\"review_not_required\")\n return {\"passed\": not failures, \"policy\": str(policy_path), \"failures\": failures}","instruction":"Explain the role of `def verify_release_policy(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_release_policy` is a function in `primitive_foundry.node_ops`. It belongs to the release area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.verify_release_policy","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.import_bus_events::explain","input":"Module: primitive_foundry.node_ops\nDomains: bus\nSource path: primitive_foundry/node_ops.py\n\ndef import_bus_events(*, adapter: str | Path, inbox: str | Path) -> dict[str, Any]:\n adapter_path = Path(adapter)\n config = json.loads(adapter_path.read_text(encoding=\"utf-8\"))\n adapter_type = config.get(\"adapter_type\")\n if adapter_type == \"nats_jetstream\":\n result = import_nats_jetstream_events(config={**config, \"adapter_path\": str(adapter_path)}, inbox=inbox)\n return {**result, \"adapter\": str(adapter_path)}\n if adapter_type != \"jsonl\":\n raise ValueError(f\"Unsupported adapter_type: {adapter_type}\")\n source = Path(config[\"source\"])\n rows = read_product_event_rows(source)\n valid_rows = []\n for row in rows:\n if row.event is None:\n continue\n valid_rows.append(\n {\n \"event_id\": row.event.event_id,\n \"text\": row.event.text,\n \"source_path\": row.event.source_path,\n \"source_id\": row.event.source_id,\n \"tags\": row.event.tags,\n \"metadata\": {**row.event.metadata, \"adapter\": str(adapter_path)},\n }\n )\n append_jsonl(Path(inbox), valid_rows)\n return {\n \"adapter\": str(adapter_path),\n \"source\": str(source),\n \"inbox\": str(inbox),\n \"imported_count\": len(valid_rows),\n \"invalid_count\": len(rows) - len(valid_rows),\n }","instruction":"Explain the role of `def import_bus_events(*, adapter: str | Path, inbox: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`import_bus_events` is a function in `primitive_foundry.node_ops`. It belongs to the bus area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.import_bus_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.install_node_service::explain","input":"Module: primitive_foundry.node_ops\nDomains: foundry\nSource path: primitive_foundry/node_ops.py\n\ndef install_node_service(\n *,\n service_file: str | Path = \"node/primitive-foundry-node.service\",\n runner_file: str | Path = \"node/run-primitive-foundry-node.sh\",\n systemd_dir: str | Path = \"~/.config/systemd/user\",\n) -> dict[str, Any]:\n target_dir = Path(systemd_dir).expanduser()\n target_dir.mkdir(parents=True, exist_ok=True)\n service_target = target_dir / Path(service_file).name\n runner_target = target_dir / Path(runner_file).name\n shutil.copyfile(service_file, service_target)\n shutil.copyfile(runner_file, runner_target)\n runner_target.chmod(0o755)\n return {\n \"installed\": True,\n \"service\": str(service_target),\n \"runner\": str(runner_target),\n \"next_commands\": [\n \"systemctl --user daemon-reload\",\n f\"systemctl --user enable --now {service_target.name}\",\n ],\n }","instruction":"Explain the role of `def install_node_service(*, service_file: str | Path='node/primitive-foundry-node.service', runner_file: str | Path='node/run-primitive-foundry-node.sh', systemd_dir: str | Path='~/.config/systemd/user') -> dict[str, Any]` in Primitive Foundry.","output":"`install_node_service` is a function in `primitive_foundry.node_ops`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.install_node_service","task":"python_symbol_explanation"} {"id":"primitive_foundry.node_ops.uninstall_node_service::explain","input":"Module: primitive_foundry.node_ops\nDomains: foundry\nSource path: primitive_foundry/node_ops.py\n\ndef uninstall_node_service(\n *,\n systemd_dir: str | Path = \"~/.config/systemd/user\",\n service_name: str = \"primitive-foundry-node.service\",\n runner_name: str = \"run-primitive-foundry-node.sh\",\n) -> dict[str, Any]:\n target_dir = Path(systemd_dir).expanduser()\n removed = []\n for name in (service_name, runner_name):\n path = target_dir / name\n if path.exists():\n path.unlink()\n removed.append(str(path))\n return {\n \"removed\": removed,\n \"next_commands\": [\"systemctl --user daemon-reload\", \"systemctl --user reset-failed\"],\n }","instruction":"Explain the role of `def uninstall_node_service(*, systemd_dir: str | Path='~/.config/systemd/user', service_name: str='primitive-foundry-node.service', runner_name: str='run-primitive-foundry-node.sh') -> dict[str, Any]` in Primitive Foundry.","output":"`uninstall_node_service` is a function in `primitive_foundry.node_ops`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.node_ops.uninstall_node_service","task":"python_symbol_explanation"} {"id":"primitive_foundry.ontologies.__init__.read_cards::explain","input":"Module: primitive_foundry.ontologies.__init__\nDomains: foundry\nSource path: primitive_foundry/ontologies/__init__.py\n\ndef read_cards(path: str | Path) -> list[dict[str, Any]]:\n rows = []\n with Path(path).open(\"r\", encoding=\"utf-8\") as handle:\n for line in handle:\n stripped = line.strip()\n if stripped:\n rows.append(json.loads(stripped))\n return rows","instruction":"Explain the role of `def read_cards(path: str | Path) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`read_cards` is a function in `primitive_foundry.ontologies.__init__`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.ontologies.__init__.read_cards","task":"python_symbol_explanation"} {"id":"primitive_foundry.ontologies.__init__.write_registry::explain","input":"Module: primitive_foundry.ontologies.__init__\nDomains: atomic_write\nSource path: primitive_foundry/ontologies/__init__.py\n\ndef write_registry(cells: list[Cell], output_path: str | Path, version: str) -> dict[str, Any]:\n registry = CellRegistry({cell.cell_id: cell for cell in cells})\n payload = registry.to_payload(registry_version=version)\n atomic_write_json(output_path, payload)\n return payload","instruction":"Explain the role of `def write_registry(cells: list[Cell], output_path: str | Path, version: str) -> dict[str, Any]` in Primitive Foundry.","output":"`write_registry` is a function in `primitive_foundry.ontologies.__init__`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.ontologies.__init__.write_registry","task":"python_symbol_explanation"} {"id":"primitive_foundry.ontologies.__init__.slug::explain","input":"Module: primitive_foundry.ontologies.__init__\nDomains: foundry\nSource path: primitive_foundry/ontologies/__init__.py\n\ndef slug(value: str) -> str:\n clean = re.sub(r\"[^a-zA-Z0-9]+\", \"_\", value.strip().lower()).strip(\"_\")\n return clean or \"unknown\"","instruction":"Explain the role of `def slug(value: str) -> str` in Primitive Foundry.","output":"`slug` is a function in `primitive_foundry.ontologies.__init__`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.ontologies.__init__.slug","task":"python_symbol_explanation"} {"id":"primitive_foundry.ontologies.agent_runtime_governance.build_registry::explain","input":"Module: primitive_foundry.ontologies.agent_runtime_governance\nDomains: source_card\nSource path: primitive_foundry/ontologies/agent_runtime_governance.py\n\ndef build_registry(source_cards_path: str | Path, output_path: str | Path) -> dict:\n cells = []\n for card in read_cards(source_cards_path):\n scenario = slug(str(card.get(\"metadata\", {}).get(\"scenario_kind\") or card.get(\"buyer_task\", {}).get(\"scenario_kind\") or \"governance\"))\n cell_id = f\"governance.{scenario}.{slug(str(card.get('record_id')))}\"\n cells.append(\n Cell(\n cell_id=cell_id,\n domain_path=f\"governance.{scenario}\",\n valid_from=str(card.get(\"valid_from\", \"2024-01-01\")),\n valid_until=card.get(\"valid_until\"),\n trust_score=0.94,\n status=\"active\",\n keywords=(\"governance\", \"authority\", \"override\", \"scheduler\", scenario),\n answer_template=f\"Honor governance scenario {scenario} with authority trace and no silent override.\",\n )\n )\n return write_registry(cells, output_path, \"agent-runtime-governance-ontology-v1\")","instruction":"Explain the role of `def build_registry(source_cards_path: str | Path, output_path: str | Path) -> dict` in Primitive Foundry.","output":"`build_registry` is a function in `primitive_foundry.ontologies.agent_runtime_governance`. It belongs to the source_card area of Primitive Foundry.","source_id":"primitive_foundry.ontologies.agent_runtime_governance.build_registry","task":"python_symbol_explanation"} {"id":"primitive_foundry.ontologies.privacy_provenance.build_registry::explain","input":"Module: primitive_foundry.ontologies.privacy_provenance\nDomains: privacy, source_card\nSource path: primitive_foundry/ontologies/privacy_provenance.py\n\ndef build_registry(source_cards_path: str | Path, output_path: str | Path) -> dict:\n cells = []\n for card in read_cards(source_cards_path):\n meta = card.get(\"metadata\", {})\n regulation = slug(str(meta.get(\"regulation_family\") or card.get(\"buyer_task\", {}).get(\"regulation_family\") or \"privacy\"))\n control = slug(str(meta.get(\"control_id\") or card.get(\"buyer_task\", {}).get(\"control_id\") or card.get(\"record_id\")))\n cell_id = f\"legal.privacy.{regulation}.{control}\"\n cells.append(\n Cell(\n cell_id=cell_id,\n domain_path=f\"legal.privacy.{regulation}\",\n valid_from=str(card.get(\"valid_from\", \"2024-01-01\")),\n valid_until=card.get(\"valid_until\"),\n trust_score=0.95,\n status=\"active\",\n keywords=(\"privacy\", \"provenance\", regulation, control),\n answer_template=f\"Apply {regulation.upper()} control {control} with provenance, sanitized export, and review evidence.\",\n )\n )\n return write_registry(cells, output_path, \"privacy-provenance-ontology-v1\")","instruction":"Explain the role of `def build_registry(source_cards_path: str | Path, output_path: str | Path) -> dict` in Primitive Foundry.","output":"`build_registry` is a function in `primitive_foundry.ontologies.privacy_provenance`. It belongs to the privacy, source_card area of Primitive Foundry.","source_id":"primitive_foundry.ontologies.privacy_provenance.build_registry","task":"python_symbol_explanation"} {"id":"primitive_foundry.paths.artifact_root::explain","input":"Module: primitive_foundry.paths\nDomains: foundry\nSource path: primitive_foundry/paths.py\n\ndef artifact_root() -> Path:\n return Path(os.environ.get(ARTIFACT_ROOT_ENV, DEFAULT_ARTIFACT_ROOT))","instruction":"Explain the role of `def artifact_root() -> Path` in Primitive Foundry.","output":"`artifact_root` is a function in `primitive_foundry.paths`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.paths.artifact_root","task":"python_symbol_explanation"} {"id":"primitive_foundry.paths.artifact_path::explain","input":"Module: primitive_foundry.paths\nDomains: foundry\nSource path: primitive_foundry/paths.py\n\ndef artifact_path(*parts: str) -> str:\n return str(artifact_root().joinpath(*parts))","instruction":"Explain the role of `def artifact_path(*parts: str) -> str` in Primitive Foundry.","output":"`artifact_path` is a function in `primitive_foundry.paths`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.paths.artifact_path","task":"python_symbol_explanation"} {"id":"primitive_foundry.primitive_bus_adapter.PrimitiveMessageView::explain","input":"Module: primitive_foundry.primitive_bus_adapter\nDomains: bus\nSource path: primitive_foundry/primitive_bus_adapter.py\n\nclass PrimitiveMessageView:\n subject: str\n payload: dict[str, Any]\n message_id: str\n timestamp: float | None = None\n source_node_id: str | None = None\n source_agent_id: str | None = None\n ack_id: str | None = None","instruction":"Explain the role of `class PrimitiveMessageView` in Primitive Foundry.","output":"`PrimitiveMessageView` is a class in `primitive_foundry.primitive_bus_adapter`. It belongs to the bus area of Primitive Foundry.","source_id":"primitive_foundry.primitive_bus_adapter.PrimitiveMessageView","task":"python_symbol_explanation"} {"id":"primitive_foundry.primitive_bus_adapter.import_nats_jetstream_events::explain","input":"Module: primitive_foundry.primitive_bus_adapter\nDomains: bus, source_card\nSource path: primitive_foundry/primitive_bus_adapter.py\n\ndef import_nats_jetstream_events(*, config: dict[str, Any], inbox: str | Path) -> dict[str, Any]:\n bus_root = config.get(\"event_bus_root\")\n if bus_root:\n root_path = Path(bus_root).expanduser()\n # Try several known kernel locations: older sibling layout,\n # ecosystem `kernel/` peer of `infra/`, plus venvs.\n kernel_candidates = [\n root_path.parent / \"context_primitive_kernel\",\n root_path.parent.parent / \"kernel\",\n root_path.parent / \"kernel\",\n ]\n for candidate in (\n root_path / \"src\",\n root_path / \".venv\" / \"lib\" / f\"python{sys.version_info.major}.{sys.version_info.minor}\" / \"site-packages\",\n ):\n source_path = str(candidate)\n if candidate.exists() and source_path not in sys.path:\n sys.path.insert(0, source_path)\n for kernel_root in kernel_candidates:\n for candidate in (\n kernel_root / \"src\",\n kernel_root / \".venv\" / \"lib\" / f\"python{sys.version_info.major}.{sys.version_info.minor}\" / \"site-packages\",\n ):\n source_path = str(candidate)\n if candidate.exists() and source_path not in sys.path:\n sys.path.insert(0, source_path)\n try:\n from primitive_event_bus.nats_transport import NatsJetStreamConfig, NatsJetStreamTransport\n except ImportError as exc:\n raise RuntimeError(\n \"primitive_event_bus NATS support is unavailable. Set adapter.event_bus_root to the \"\n \"primitive-event-bus workspace or install primitive-event-bus[nats].\"\n ) from exc\n\n subjects = tuple(config.get(\"subjects\") or DEFAULT_KERNEL_PRODUCT_SUBJECTS)\n durable = str(config.get(\"durable\") or \"primitive-foundry-importer\")\n batch = int(config.get(\"batch\") or 25)\n ack = bool(config.get(\"ack\", True))\n transport = NatsJetStreamTransport(\n NatsJetStreamConfig(\n servers=(str(config.get(\"nats_url\") or \"nats://127.0.0.1:4222\"),),\n stream_name=str(config.get(\"stream\") or \"PRIMITIVE\"),\n storage=str(config.get(\"storage\") or \"file\"),\n replicas=int(config.get(\"replicas\") or 1),\n )\n )\n\n imported_rows = []\n imported_source_cards = []\n pulled_count = 0\n acked_count = 0\n source_cache_dir = config.get(\"source_cache_dir\") or Path(inbox).parent / \"primitive_bus_sources\"\n for subject in subjects:\n messages = transport.pull(subject, durable=f\"{durable}-{subject.replace('.', '-')}\", batch=batch)\n pulled_count += len(messages)\n message_views = [\n PrimitiveMessageView(\n subject=message.subject,\n payload=message.payload,\n message_id=message.message_id,\n timestamp=message.timestamp,\n source_node_id=message.source_node_id,\n source_agent_id=message.source_agent_id,\n ack_id=message.ack_id,\n )\n for message in messages\n ]\n rows = primitive_messages_to_product_rows(\n message_views,\n source_cache_dir=source_cache_dir,\n )\n imported_rows.extend(rows)\n imported_source_cards.extend(primitive_messages_to_source_cards(message_views, source_cache_dir=source_cache_dir))\n if ack:\n for message in messages:\n if message.ack_id:\n transport.ack(message.ack_id)\n acked_count += 1\n if imported_rows:\n append_jsonl(Path(inbox), imported_rows)\n source_cards_path = config.get(\"source_cards_path\")\n if source_cards_path and imported_source_cards:\n append_jsonl(Path(source_cards_path), imported_source_cards)\n return {\n \"adapter_type\": \"nats_jetstream\",\n \"nats_url\": str(config.get(\"nats_url\") or \"nats://127.0.0.1:4222\"),\n \"stream\": str(config.get(\"stream\") or \"PRIMITIVE\"),\n \"subjects\": list(subjects),\n \"durable\": durable,\n \"inbox\": str(inbox),\n \"pulled_count\": pulled_count,\n \"imported_count\": len(imported_rows),\n \"source_card_count\": len(imported_source_cards),\n \"source_cards_path\": str(source_cards_path) if source_cards_path else None,\n \"acked_count\": acked_count,\n \"ack\": ack,\n }","instruction":"Explain the role of `def import_nats_jetstream_events(*, config: dict[str, Any], inbox: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`import_nats_jetstream_events` is a function in `primitive_foundry.primitive_bus_adapter`. It belongs to the bus, source_card area of Primitive Foundry.","source_id":"primitive_foundry.primitive_bus_adapter.import_nats_jetstream_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.primitive_bus_adapter.primitive_messages_to_product_rows::explain","input":"Module: primitive_foundry.primitive_bus_adapter\nDomains: bus, dataset\nSource path: primitive_foundry/primitive_bus_adapter.py\n\ndef primitive_messages_to_product_rows(\n messages: list[PrimitiveMessageView],\n *,\n source_cache_dir: str | Path,\n) -> list[dict[str, Any]]:\n cache_dir = Path(source_cache_dir)\n cache_dir.mkdir(parents=True, exist_ok=True)\n rows = []\n for message in messages:\n text = sterilize_text(extract_product_text(message.subject, message.payload)).text\n if not text.strip():\n continue\n source_id = str(message.payload.get(\"event_id\") or message.payload.get(\"source_event_id\") or message.message_id)\n source_path = write_source_cache(cache_dir, message, text)\n rows.append(\n {\n \"event_id\": f\"primitive:{message.subject}:{message.message_id}\",\n \"text\": text,\n \"source_path\": str(source_path),\n \"source_id\": source_id,\n \"tags\": primitive_tags(message.subject, message.payload),\n \"metadata\": {\n \"adapter\": \"nats_jetstream\",\n \"primitive_subject\": message.subject,\n \"primitive_message_id\": message.message_id,\n \"primitive_timestamp\": message.timestamp,\n \"source_node_id\": message.source_node_id,\n \"source_agent_id\": message.source_agent_id,\n \"dataset_family\": message.payload.get(\"dataset_family\"),\n \"source_family\": message.payload.get(\"source_family\"),\n \"product_kind\": message.payload.get(\"product_kind\"),\n \"task_category\": message.payload.get(\"task_category\"),\n \"payload_keys\": sorted(str(key) for key in message.payload.keys()),\n \"source_hash\": sha256_json({\"subject\": message.subject, \"payload\": message.payload}),\n },\n }\n )\n return rows","instruction":"Explain the role of `def primitive_messages_to_product_rows(messages: list[PrimitiveMessageView], *, source_cache_dir: str | Path) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`primitive_messages_to_product_rows` is a function in `primitive_foundry.primitive_bus_adapter`. It belongs to the bus, dataset area of Primitive Foundry.","source_id":"primitive_foundry.primitive_bus_adapter.primitive_messages_to_product_rows","task":"python_symbol_explanation"} {"id":"primitive_foundry.primitive_bus_adapter.primitive_messages_to_source_cards::explain","input":"Module: primitive_foundry.primitive_bus_adapter\nDomains: sterilization, bus, source_card\nSource path: primitive_foundry/primitive_bus_adapter.py\n\ndef primitive_messages_to_source_cards(\n messages: list[PrimitiveMessageView],\n *,\n source_cache_dir: str | Path,\n) -> list[dict[str, Any]]:\n cache_dir = Path(source_cache_dir)\n cache_dir.mkdir(parents=True, exist_ok=True)\n cards: list[dict[str, Any]] = []\n for message in messages:\n payload = normalize_source_card_payload(message)\n if payload is None:\n continue\n source_path = write_source_card_cache(cache_dir, message, payload)\n source_family = str(payload.get(\"source_family\") or \"agent_runtime_governance\")\n domain_path = str(payload.get(\"domain_path\") or \"operations.governance\")\n task = str(payload.get(\"task\") or \"honor_governance_rule\")\n rubric_id = str(payload.get(\"rubric_id\") or \"rubric.governance.v1\")\n record_id = str(payload.get(\"record_id\") or f\"bus-source-card-{message.message_id}\")\n source_id = str(payload.get(\"source_id\") or record_id)\n tags = [str(item) for item in payload.get(\"tags\", []) if str(item).strip()] if isinstance(payload.get(\"tags\"), list) else []\n if source_family not in tags:\n tags.append(source_family)\n cards.append(\n {\n \"record_id\": record_id,\n \"source_id\": source_id,\n \"source_path\": str(source_path),\n \"source_summary\": f\"Event-bus source card {source_id} for {task}\",\n \"source_line_hint\": f\"event-bus:{message.subject}:{message.message_id}\",\n \"domain_path\": domain_path,\n \"query\": f\"Process event-bus source card {source_id} for {task} in {domain_path}.\",\n \"expected_answer\": f\"{domain_path}.2024\",\n \"expected_cell_id\": f\"{domain_path}.2024\",\n \"expected_cell_ids\": [f\"{domain_path}.2024\"],\n \"task\": task,\n \"source_family\": source_family,\n \"tags\": sorted(set(tags + [\"event-bus\", \"primitive-bus\"])),\n \"rubric\": {\n \"rubric_id\": rubric_id,\n \"pass_conditions\": [\"event_bus_source_card_received\", \"source_binding_preserved\"],\n },\n \"buyer_task\": {\n \"family\": source_family,\n \"rubric_id\": rubric_id,\n \"source_id\": source_id,\n },\n \"domain_review\": {\n \"review_status\": \"founder_attested_v1\",\n \"reviewer_name\": \"local-owner\",\n \"reviewer_credentials\": \"Event-bus source-card intake review; SME review pending\",\n \"reviewed_at\": \"2026-05-13\",\n },\n \"metadata\": {\n \"adapter\": str(payload.get(\"adapter\") or \"primitive_event_bus_source_card\"),\n \"origin_adapter\": \"primitive_event_bus_source_card\",\n \"sterilization_ruleset\": \"agent_traces\",\n \"primitive_subject\": message.subject,\n \"primitive_message_id\": message.message_id,\n \"primitive_timestamp\": message.timestamp,\n \"source_node_id\": message.source_node_id,\n \"source_agent_id\": message.source_agent_id,\n \"coordination\": payload.get(\"coordination\"),\n \"raw_private\": payload.get(\"raw_private\"),\n \"export_allowed\": payload.get(\"export_allowed\"),\n \"source_hash\": sha256_json({\"subject\": message.subject, \"payload\": payload}),\n },\n }\n )\n return cards","instruction":"Explain the role of `def primitive_messages_to_source_cards(messages: list[PrimitiveMessageView], *, source_cache_dir: str | Path) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`primitive_messages_to_source_cards` is a function in `primitive_foundry.primitive_bus_adapter`. It belongs to the sterilization, bus, source_card area of Primitive Foundry.","source_id":"primitive_foundry.primitive_bus_adapter.primitive_messages_to_source_cards","task":"python_symbol_explanation"} {"id":"primitive_foundry.primitive_bus_adapter.normalize_source_card_payload::explain","input":"Module: primitive_foundry.primitive_bus_adapter\nDomains: bus, source_card\nSource path: primitive_foundry/primitive_bus_adapter.py\n\ndef normalize_source_card_payload(message: PrimitiveMessageView) -> dict[str, Any] | None:\n if message.subject != SOURCE_CARD_EVENT_TYPE and message.payload.get(\"event_type\") != SOURCE_CARD_EVENT_TYPE:\n return None\n payload = message.payload.get(\"payload\") if isinstance(message.payload.get(\"payload\"), dict) else message.payload\n if not isinstance(payload, dict):\n return None\n if payload.get(\"coordination\") != \"event-bus-only\":\n return None\n if payload.get(\"raw_private\") is not True:\n return None\n if not payload.get(\"record_id\") or not payload.get(\"source_id\"):\n return None\n return payload","instruction":"Explain the role of `def normalize_source_card_payload(message: PrimitiveMessageView) -> dict[str, Any] | None` in Primitive Foundry.","output":"`normalize_source_card_payload` is a function in `primitive_foundry.primitive_bus_adapter`. It belongs to the bus, source_card area of Primitive Foundry.","source_id":"primitive_foundry.primitive_bus_adapter.normalize_source_card_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.primitive_bus_adapter.extract_product_text::explain","input":"Module: primitive_foundry.primitive_bus_adapter\nDomains: bus, dataset\nSource path: primitive_foundry/primitive_bus_adapter.py\n\ndef extract_product_text(subject: str, payload: dict[str, Any]) -> str:\n parts = [subject.replace(\".\", \" \")]\n for key in (\"text\", \"summary\", \"content\", \"description\", \"title\", \"name\", \"status\", \"outcome\", \"reason\"):\n value = payload.get(key)\n if isinstance(value, str) and value.strip():\n parts.append(value.strip())\n for key in (\"family\", \"dataset_family\", \"product_kind\", \"task_category\", \"event_type\", \"quality_label\"):\n value = payload.get(key)\n if isinstance(value, str) and value.strip():\n parts.append(value.strip())\n if len(parts) == 1:\n parts.append(json.dumps(payload, sort_keys=True))\n return \" \".join(parts)","instruction":"Explain the role of `def extract_product_text(subject: str, payload: dict[str, Any]) -> str` in Primitive Foundry.","output":"`extract_product_text` is a function in `primitive_foundry.primitive_bus_adapter`. It belongs to the bus, dataset area of Primitive Foundry.","source_id":"primitive_foundry.primitive_bus_adapter.extract_product_text","task":"python_symbol_explanation"} {"id":"primitive_foundry.primitive_bus_adapter.primitive_tags::explain","input":"Module: primitive_foundry.primitive_bus_adapter\nDomains: bus, dataset\nSource path: primitive_foundry/primitive_bus_adapter.py\n\ndef primitive_tags(subject: str, payload: dict[str, Any]) -> list[str]:\n tags = {subject, *subject.split(\".\")}\n raw_tags = payload.get(\"tags\")\n if isinstance(raw_tags, list):\n tags.update(str(item) for item in raw_tags if str(item).strip())\n for key in (\"family\", \"dataset_family\", \"product_kind\", \"task_category\", \"event_type\"):\n value = payload.get(key)\n if isinstance(value, str) and value.strip():\n tags.add(value.strip())\n if \"dataset\" in subject:\n tags.add(\"dataset\")\n if \"receipt\" in subject or \"authority\" in subject:\n tags.add(\"provenance\")\n if \"task\" in subject:\n tags.add(\"eval\")\n return sorted(tags)","instruction":"Explain the role of `def primitive_tags(subject: str, payload: dict[str, Any]) -> list[str]` in Primitive Foundry.","output":"`primitive_tags` is a function in `primitive_foundry.primitive_bus_adapter`. It belongs to the bus, dataset area of Primitive Foundry.","source_id":"primitive_foundry.primitive_bus_adapter.primitive_tags","task":"python_symbol_explanation"} {"id":"primitive_foundry.primitive_bus_adapter.write_source_card_cache::explain","input":"Module: primitive_foundry.primitive_bus_adapter\nDomains: bus, source_card\nSource path: primitive_foundry/primitive_bus_adapter.py\n\ndef write_source_card_cache(cache_dir: Path, message: PrimitiveMessageView, payload: dict[str, Any]) -> Path:\n digest = sha256_json({\"subject\": message.subject, \"message_id\": message.message_id, \"payload\": payload})[:20]\n path = cache_dir / f\"{digest}.source-card.json\"\n cache_payload = {\n \"manifest_type\": \"aml_primitive_bus_source_card_cache\",\n \"subject\": message.subject,\n \"message_id\": message.message_id,\n \"source_node_id\": message.source_node_id,\n \"source_agent_id\": message.source_agent_id,\n \"payload_hash\": sha256_json(payload),\n \"record_id\": payload.get(\"record_id\"),\n \"source_id\": payload.get(\"source_id\"),\n \"source_family\": payload.get(\"source_family\"),\n \"domain_path\": payload.get(\"domain_path\"),\n \"rubric_id\": payload.get(\"rubric_id\"),\n \"coordination\": payload.get(\"coordination\"),\n }\n cache_payload[\"cache_hash\"] = sha256_json({**cache_payload, \"cache_hash\": \"\"})\n path.write_text(json.dumps(cache_payload, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return path","instruction":"Explain the role of `def write_source_card_cache(cache_dir: Path, message: PrimitiveMessageView, payload: dict[str, Any]) -> Path` in Primitive Foundry.","output":"`write_source_card_cache` is a function in `primitive_foundry.primitive_bus_adapter`. It belongs to the bus, source_card area of Primitive Foundry.","source_id":"primitive_foundry.primitive_bus_adapter.write_source_card_cache","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.ProductEvent::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\nclass ProductEvent:\n event_id: str\n text: str\n source_path: str\n source_id: str | None = None\n tags: list[str] = field(default_factory=list)\n metadata: dict[str, Any] = field(default_factory=dict)\n\n @classmethod\n def from_dict(cls, data: dict[str, Any], index: int) -> \"ProductEvent\":\n text = str(data.get(\"text\") or data.get(\"summary\") or data.get(\"content\") or \"\").strip()\n if not text:\n raise ValueError(f\"Product event {index} has no text/summary/content field.\")\n source_path = str(data.get(\"source_path\") or data.get(\"path\") or \"\").strip()\n if not source_path:\n raise ValueError(f\"Product event {index} has no source_path/path field.\")\n return cls(\n event_id=str(data.get(\"event_id\") or data.get(\"id\") or f\"event-{index:06d}\"),\n text=text,\n source_path=source_path,\n source_id=str(data.get(\"source_id\")) if data.get(\"source_id\") else None,\n tags=list(data.get(\"tags\", [])),\n metadata=dict(data.get(\"metadata\", {})),\n )","instruction":"Explain the role of `class ProductEvent` in Primitive Foundry.","output":"`ProductEvent` is a class in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.ProductEvent","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.ProductClassification::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\nclass ProductClassification:\n event_id: str\n product_kind: str\n domain_path: str\n value_tier: str\n value_score: float\n accepted: bool\n reasons: list[str]","instruction":"Explain the role of `class ProductClassification` in Primitive Foundry.","output":"`ProductClassification` is a class in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.ProductClassification","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.ProductEventRow::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\nclass ProductEventRow:\n line_number: int\n raw: dict[str, Any]\n event: ProductEvent | None\n error: str | None = None","instruction":"Explain the role of `class ProductEventRow` in Primitive Foundry.","output":"`ProductEventRow` is a class in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.ProductEventRow","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.read_product_events::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef read_product_events(path: str | Path) -> list[ProductEvent]:\n events: list[ProductEvent] = []\n with Path(path).open(\"r\", encoding=\"utf-8\") as handle:\n for index, line in enumerate(handle, start=1):\n stripped = line.strip()\n if not stripped:\n continue\n events.append(ProductEvent.from_dict(json.loads(stripped), index))\n return events","instruction":"Explain the role of `def read_product_events(path: str | Path) -> list[ProductEvent]` in Primitive Foundry.","output":"`read_product_events` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.read_product_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.read_product_event_rows::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef read_product_event_rows(path: str | Path) -> list[ProductEventRow]:\n rows: list[ProductEventRow] = []\n with Path(path).open(\"r\", encoding=\"utf-8\") as handle:\n for index, line in enumerate(handle, start=1):\n stripped = line.strip()\n if not stripped:\n continue\n try:\n raw = json.loads(stripped)\n rows.append(ProductEventRow(index, raw, ProductEvent.from_dict(raw, index)))\n except (json.JSONDecodeError, ValueError) as exc:\n rows.append(ProductEventRow(index, {\"raw_line\": stripped}, None, str(exc)))\n return rows","instruction":"Explain the role of `def read_product_event_rows(path: str | Path) -> list[ProductEventRow]` in Primitive Foundry.","output":"`read_product_event_rows` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.read_product_event_rows","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.classify_event::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef classify_event(event: ProductEvent, min_value_score: float = MEDIUM_VALUE_THRESHOLD) -> ProductClassification:\n return classify_event_with_mode(event, min_value_score=min_value_score, classifier=\"deterministic\")","instruction":"Explain the role of `def classify_event(event: ProductEvent, min_value_score: float=MEDIUM_VALUE_THRESHOLD) -> ProductClassification` in Primitive Foundry.","output":"`classify_event` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.classify_event","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.classify_event_with_mode::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef classify_event_with_mode(\n event: ProductEvent,\n min_value_score: float = MEDIUM_VALUE_THRESHOLD,\n classifier: str = \"deterministic\",\n) -> ProductClassification:\n if classifier not in {\"deterministic\", \"hashed\"}:\n raise ValueError(f\"Unsupported classifier: {classifier}\")\n text = \" \".join([event.text, \" \".join(event.tags), json.dumps(event.metadata, sort_keys=True)]).lower()\n kind = max(PRODUCT_KINDS, key=lambda item: keyword_score(text, KIND_KEYWORDS[item]))\n domain = max(DOMAIN_KEYWORDS, key=lambda item: keyword_score(text, DOMAIN_KEYWORDS[item]))\n reasons = matched_keywords(text, VALUE_KEYWORDS)\n\n score = 0.32\n score += min(0.28, 0.035 * len(reasons))\n score += 0.12 if resolve_source_path(event.source_path, source_id=event.source_id).exists() else -0.25\n score += 0.1 if keyword_score(text, KIND_KEYWORDS[kind]) > 0 else 0.0\n score += 0.08 if keyword_score(text, DOMAIN_KEYWORDS[domain]) > 0 else 0.0\n score += 0.05 if len(event.text) >= 80 else 0.0\n if classifier == \"hashed\":\n score += min(0.08, 0.01 * len(event_fingerprint(event)))\n score = round(max(0.0, min(1.0, score)), 4)\n\n if score >= HIGH_VALUE_THRESHOLD:\n tier = \"high\"\n elif score >= MEDIUM_VALUE_THRESHOLD:\n tier = \"medium\"\n else:\n tier = \"low\"\n return ProductClassification(\n event_id=event.event_id,\n product_kind=kind,\n domain_path=domain,\n value_tier=tier,\n value_score=score,\n accepted=score >= min_value_score,\n reasons=reasons,\n )","instruction":"Explain the role of `def classify_event_with_mode(event: ProductEvent, min_value_score: float=MEDIUM_VALUE_THRESHOLD, classifier: str='deterministic') -> ProductClassification` in Primitive Foundry.","output":"`classify_event_with_mode` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.classify_event_with_mode","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.run_event_stream::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef run_event_stream(\n *,\n events_path: str | Path,\n output_root: str | Path = \"products\",\n state_path: str | Path | None = None,\n batch_size: int = 25,\n min_value_score: float = MEDIUM_VALUE_THRESHOLD,\n reviewer: str = \"local-owner\",\n approve: bool = True,\n iterations: int = 1,\n poll_seconds: float = 5.0,\n min_records: int = 1,\n min_source_diversity: int = 1,\n require_product_kinds: tuple[str, ...] = (),\n dedupe_threshold: float = 0.92,\n classifier: str = \"deterministic\",\n) -> dict[str, Any]:\n if iterations < 0:\n raise ValueError(\"iterations must be >= 0\")\n results = []\n count = 0\n while True:\n results.append(\n process_event_stream_once(\n events_path=events_path,\n output_root=output_root,\n state_path=state_path,\n batch_size=batch_size,\n min_value_score=min_value_score,\n reviewer=reviewer,\n approve=approve,\n min_records=min_records,\n min_source_diversity=min_source_diversity,\n require_product_kinds=require_product_kinds,\n dedupe_threshold=dedupe_threshold,\n classifier=classifier,\n )\n )\n count += 1\n if iterations and count >= iterations:\n break\n if iterations == 0 or count < iterations:\n time.sleep(poll_seconds)\n return {\n \"stream\": \"aml_product_stream\",\n \"iterations\": len(results),\n \"candidates_created\": sum(1 for item in results if item[\"new_candidate\"]),\n \"results\": results,\n \"passed\": all(item[\"passed\"] for item in results),\n }","instruction":"Explain the role of `def run_event_stream(*, events_path: str | Path, output_root: str | Path='products', state_path: str | Path | None=None, batch_size: int=25, min_value_score: float=MEDIUM_VALUE_THRESHOLD, reviewer: str='local-owner', approve: bool=True, iterations: int=1, poll_seconds: float=5.0, min_records: int=1, min_source_diversity: int=1, require_product_kinds: tuple[str, ...]=(), dedupe_threshold: float=0.92, classifier: str='deterministic') -> dict[str, Any]` in Primitive Foundry.","output":"`run_event_stream` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.run_event_stream","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.build_candidate_from_events::explain","input":"Module: primitive_foundry.product_factory\nDomains: sterilization, release, dataset, router, benchmark, source_card, product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef build_candidate_from_events(\n *,\n events_path: str | Path,\n output_root: str | Path = \"products\",\n candidate_id: str | None = None,\n min_value_score: float = MEDIUM_VALUE_THRESHOLD,\n reviewer: str = \"local-owner\",\n approve: bool = True,\n max_records: int | None = None,\n min_records: int = 1,\n min_source_diversity: int = 1,\n require_product_kinds: tuple[str, ...] = (),\n classifier: str = \"deterministic\",\n) -> dict[str, Any]:\n events = read_product_events(events_path)\n if not events:\n raise ValueError(\"No product events found.\")\n if not candidate_id:\n candidate_id = \"aml_candidate_\" + datetime.now(timezone.utc).strftime(\"%Y%m%d_%H%M%S\")\n\n root = Path(output_root)\n candidate_dir = root / candidate_id\n candidate_dir.mkdir(parents=True, exist_ok=True)\n\n classified = [(event, classify_event_with_mode(event, min_value_score, classifier)) for event in events]\n accepted = [(event, item) for event, item in classified if item.accepted]\n if max_records is not None:\n accepted = accepted[:max_records]\n if not accepted:\n raise ValueError(\"No medium/high-value events passed product classification.\")\n gate_preview = evaluate_product_quality_gates(\n accepted,\n min_records=min_records,\n min_source_diversity=min_source_diversity,\n require_product_kinds=require_product_kinds,\n benchmark_pass_rate=None,\n foundry_passed=None,\n bundle_passed=None,\n sterilization_passed=None,\n promotion_passed=None,\n review_passed=None,\n release_index_passed=None,\n )\n\n cards_path = candidate_dir / \"source_cards.jsonl\"\n dataset_path = candidate_dir / \"dataset.jsonl\"\n foundry_path = candidate_dir / \"foundry_records.jsonl\"\n bundle_dir = candidate_dir / \"bundle\"\n summary_path = candidate_dir / \"router_summary.json\"\n report_card_path = candidate_dir / \"REPORT_CARD.md\"\n lock_path = candidate_dir / \"MANIFEST.lock\"\n promotions_dir = root / \"promotions\"\n reviews_dir = root / \"reviews\"\n promotion_path = promotions_dir / f\"{candidate_id}.promotion.json\"\n review_path = reviews_dir / f\"{candidate_id}.review.json\"\n release_index_path = root / \"RELEASE_INDEX.json\"\n catalog_path = root / \"PRODUCT_CATALOG.json\"\n\n write_source_cards(accepted, cards_path, candidate_id, reviewer=reviewer)\n curated = curate_source_cards(cards_path, dataset_path)\n benchmark = BenchmarkRunner(router_name=\"keyword\").run_dataset(dataset_path)\n summary = router_summary(dataset_path)\n write_summary(summary, summary_path)\n foundry = export_foundry_records(dataset_path, foundry_path)\n bundle = build_foundry_bundle(foundry_path, bundle_dir, dataset_name=candidate_id)\n bundle_verify = verify_foundry_bundle(bundle_dir)\n quality_gates = evaluate_product_quality_gates(\n accepted,\n min_records=min_records,\n min_source_diversity=min_source_diversity,\n require_product_kinds=require_product_kinds,\n benchmark_pass_rate=float(benchmark[\"pass_rate\"]),\n foundry_passed=bool(foundry[\"quality\"][\"passed\"]),\n bundle_passed=bool(bundle_verify[\"passed\"]),\n sterilization_passed=bool(bundle_verify.get(\"sterilization\", {}).get(\"passed\")),\n promotion_passed=None,\n review_passed=None,\n release_index_passed=None,\n )\n can_promote = all(gate[\"passed\"] for gate in quality_gates if gate[\"actual\"] is not None)\n promotion = promote_bundle(\n dataset_path=dataset_path,\n foundry_records=foundry_path,\n bundle_dir=bundle_dir,\n output_manifest=promotion_path,\n router=\"keyword\",\n require_audit=False,\n min_pass_rate=1.0 if can_promote else 2.0,\n )\n promotion_verify = verify_promotion_manifest(promotion_path)\n review = None\n review_verify = None\n if approve and promotion_verify[\"passed\"]:\n review = review_promotion(\n manifest_path=promotion_path,\n reviewer=reviewer,\n decision=\"approved\",\n notes=\"Auto-approved local private product candidate after passing gates.\",\n output_path=review_path,\n )\n review_verify = verify_review_manifest(review_path)\n index = build_release_index(promotions_dir=promotions_dir, reviews_dir=reviews_dir, output_path=release_index_path)\n index_verify = verify_release_index(release_index_path)\n quality_gates = evaluate_product_quality_gates(\n accepted,\n min_records=min_records,\n min_source_diversity=min_source_diversity,\n require_product_kinds=require_product_kinds,\n benchmark_pass_rate=float(benchmark[\"pass_rate\"]),\n foundry_passed=bool(foundry[\"quality\"][\"passed\"]),\n bundle_passed=bool(bundle_verify[\"passed\"]),\n sterilization_passed=bool(bundle_verify.get(\"sterilization\", {}).get(\"passed\")),\n promotion_passed=bool(promotion_verify[\"passed\"]),\n review_passed=bool(review_verify[\"passed\"]) if review_verify else None,\n release_index_passed=bool(index_verify[\"passed\"]),\n )\n\n product_mix = product_mix_from_classifications([item for _, item in accepted])\n lock = write_manifest_lock(\n lock_path,\n {\n \"candidate_id\": candidate_id,\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"events_path\": str(events_path),\n \"accepted_event_count\": len(accepted),\n \"rejected_event_count\": len(classified) - len(accepted),\n \"product_mix\": product_mix,\n \"classifier\": classifier,\n \"product_economics\": product_economics(accepted, benchmark[\"pass_rate\"]),\n \"artifacts\": {\n \"source_cards\": str(cards_path),\n \"dataset\": str(dataset_path),\n \"foundry_records\": str(foundry_path),\n \"bundle_dir\": str(bundle_dir),\n \"router_summary\": str(summary_path),\n \"promotion\": str(promotion_path),\n \"review\": str(review_path) if review else None,\n \"report_card\": str(report_card_path),\n },\n \"ledgers\": {\n \"release_index\": str(release_index_path),\n \"product_catalog\": str(catalog_path),\n },\n \"quality\": {\n \"quality_gates\": quality_gates,\n \"quality_gate_preview\": gate_preview,\n \"benchmark_pass_rate\": benchmark[\"pass_rate\"],\n \"foundry_passed\": foundry[\"quality\"][\"passed\"],\n \"bundle_passed\": bundle_verify[\"passed\"],\n \"sterilization_passed\": bundle_verify.get(\"sterilization\", {}).get(\"passed\"),\n \"promotion_passed\": promotion_verify[\"passed\"],\n \"review_passed\": review_verify[\"passed\"] if review_verify else None,\n \"release_index_passed\": index_verify[\"passed\"],\n },\n \"hashes\": {},\n },\n )\n write_report_card(\n report_card_path,\n candidate_id=candidate_id,\n accepted=[item for _, item in accepted],\n curated=curated,\n benchmark=benchmark,\n foundry=foundry,\n bundle=bundle,\n bundle_verify=bundle_verify,\n promotion=promotion,\n promotion_verify=promotion_verify,\n review=review,\n review_verify=review_verify,\n index=index,\n index_verify=index_verify,\n lock=lock,\n )\n lock = write_manifest_lock(lock_path, {**lock, \"hashes\": artifact_hashes(lock[\"artifacts\"])})\n catalog = update_product_catalog(catalog_path, candidate_id, lock, promotion_verify, review_verify)\n return {\n \"candidate_id\": candidate_id,\n \"candidate_dir\": str(candidate_dir),\n \"accepted_event_count\": len(accepted),\n \"rejected_event_count\": len(classified) - len(accepted),\n \"product_mix\": product_mix,\n \"product_economics\": product_economics(accepted, benchmark[\"pass_rate\"]),\n \"dataset\": str(dataset_path),\n \"bundle_dir\": str(bundle_dir),\n \"promotion\": str(promotion_path),\n \"review\": str(review_path) if review else None,\n \"release_index\": str(release_index_path),\n \"report_card\": str(report_card_path),\n \"manifest_lock\": str(lock_path),\n \"catalog\": str(catalog_path),\n \"catalog_count\": len(catalog[\"products\"]),\n \"quality_gates\": quality_gates,\n \"passed\": all(gate[\"passed\"] for gate in quality_gates),\n }","instruction":"Explain the role of `def build_candidate_from_events(*, events_path: str | Path, output_root: str | Path='products', candidate_id: str | None=None, min_value_score: float=MEDIUM_VALUE_THRESHOLD, reviewer: str='local-owner', approve: bool=True, max_records: int | None=None, min_records: int=1, min_source_diversity: int=1, require_product_kinds: tuple[str, ...]=(), classifier: str='deterministic') -> dict[str, Any]` in Primitive Foundry.","output":"`build_candidate_from_events` is a function in `primitive_foundry.product_factory`. It belongs to the sterilization, release, dataset, router, benchmark, source_card, product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.build_candidate_from_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.load_stream_state::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef load_stream_state(path: Path) -> dict[str, Any]:\n if not path.exists():\n return {\n \"manifest_type\": \"aml_product_stream_state\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"updated_at\": None,\n \"candidate_sequence\": 0,\n \"processed_event_ids\": [],\n \"candidates\": [],\n }\n state = json.loads(path.read_text(encoding=\"utf-8\"))\n if state.get(\"manifest_type\") != \"aml_product_stream_state\":\n raise ValueError(f\"Invalid stream state manifest: {path}\")\n return state","instruction":"Explain the role of `def load_stream_state(path: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`load_stream_state` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.load_stream_state","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.save_stream_state::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef save_stream_state(path: Path, state: dict[str, Any]) -> None:\n payload = {**state, \"state_hash\": \"\"}\n payload[\"state_hash\"] = sha256_json(payload)\n path.parent.mkdir(parents=True, exist_ok=True)\n tmp = path.with_suffix(path.suffix + \".tmp\")\n tmp.write_text(json.dumps(payload, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n tmp.replace(path)","instruction":"Explain the role of `def save_stream_state(path: Path, state: dict[str, Any]) -> None` in Primitive Foundry.","output":"`save_stream_state` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.save_stream_state","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.verify_stream_state::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef verify_stream_state(path: str | Path) -> dict[str, Any]:\n state_path = Path(path)\n state = json.loads(state_path.read_text(encoding=\"utf-8\"))\n expected = sha256_json({**state, \"state_hash\": \"\"})\n failures = []\n if state.get(\"manifest_type\") != \"aml_product_stream_state\":\n failures.append(\"invalid_manifest_type\")\n if state.get(\"state_hash\") != expected:\n failures.append(\"state_hash_mismatch\")\n ids = list(state.get(\"processed_event_ids\", []))\n if len(ids) != len(set(ids)):\n failures.append(\"duplicate_processed_event_ids\")\n return {\n \"passed\": not failures,\n \"state_path\": str(state_path),\n \"processed_event_count\": len(ids),\n \"candidate_count\": len(state.get(\"candidates\", [])),\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_stream_state(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_stream_state` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.verify_stream_state","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.write_source_cards::explain","input":"Module: primitive_foundry.product_factory\nDomains: sterilization, bus, planner, source_card, product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef write_source_cards(\n accepted: list[tuple[ProductEvent, ProductClassification]],\n output_path: Path,\n candidate_id: str,\n reviewer: str = \"local-owner\",\n) -> None:\n rows = []\n for index, (event, classification) in enumerate(accepted, start=1):\n source_path = resolve_source_path(event.source_path, source_id=event.source_id)\n if not source_path.exists():\n raise FileNotFoundError(f\"Accepted event source path does not exist: {source_path}\")\n sterile_summary = sterilize_text(event.text, max_chars=240)\n planner_family = str(event.metadata.get(\"planner_family\") or \"\")\n family = planner_family if planner_family in GENERATOR_REGISTRY else FAMILY_BY_KIND[classification.product_kind]\n generator = GENERATOR_REGISTRY[family] if family in GENERATOR_REGISTRY else GENERATOR_REGISTRY[classification.product_kind]\n source_card = SourceCard(\n record_id=f\"{candidate_id}-{index:04d}\",\n source_id=event.source_id or event.event_id,\n source_path=str(source_path),\n source_summary=sterile_summary.text,\n source_line_hint=event.metadata.get(\"line_hint\", \"event bus product source\"),\n domain_path=classification.domain_path,\n tags=event.tags\n + [\n classification.product_kind,\n classification.value_tier,\n family,\n \"event_bus\",\n \"sale_candidate\",\n \"sterilized\",\n ],\n sterilization=sterile_summary.to_dict(),\n )\n card = generator.build_record(source_card, index)\n card.setdefault(\"metadata\", {})\n card[\"metadata\"] = {\n **card[\"metadata\"],\n \"input_product_kind\": classification.product_kind,\n \"planner_family\": family,\n \"value_tier\": classification.value_tier,\n \"value_score\": classification.value_score,\n }\n rows.append(card)\n write_jsonl(output_path, rows)","instruction":"Explain the role of `def write_source_cards(accepted: list[tuple[ProductEvent, ProductClassification]], output_path: Path, candidate_id: str, reviewer: str='local-owner') -> None` in Primitive Foundry.","output":"`write_source_cards` is a function in `primitive_foundry.product_factory`. It belongs to the sterilization, bus, planner, source_card, product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.write_source_cards","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.query_for_product::explain","input":"Module: primitive_foundry.product_factory\nDomains: dataset, benchmark, compliance, product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef query_for_product(event: ProductEvent, classification: ProductClassification) -> str:\n domain_phrase = classification.domain_path.replace(\".\", \" \")\n sterile_text = sterilize_text(event.text, max_chars=160).text\n if classification.product_kind == \"dataset\":\n return (\n f\"Route this private dataset product source to the active {domain_phrase} \"\n f\"compliance routing cell: {sterile_text}\"\n )\n if classification.product_kind == \"eval_harness\":\n return (\n f\"Audit the {domain_phrase} provenance compliance and quality gate for this \"\n f\"private eval harness source: {sterile_text}\"\n )\n return (\n f\"Benchmark {domain_phrase} routing and replacement behavior for this private \"\n f\"source-backed product: {sterile_text}\"\n )","instruction":"Explain the role of `def query_for_product(event: ProductEvent, classification: ProductClassification) -> str` in Primitive Foundry.","output":"`query_for_product` is a function in `primitive_foundry.product_factory`. It belongs to the dataset, benchmark, compliance, product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.query_for_product","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.write_report_card::explain","input":"Module: primitive_foundry.product_factory\nDomains: release, benchmark, product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef write_report_card(path: Path, **payload: Any) -> None:\n candidate_id = payload[\"candidate_id\"]\n lock = payload[\"lock\"]\n lines = [\n f\"# Primitive Foundry Product Candidate: {candidate_id}\",\n \"\",\n \"Private local release candidate. Raw source text is not embedded in exported records.\",\n \"\",\n \"## Product Mix\",\n ]\n mix = product_mix_from_classifications(payload[\"accepted\"])\n for key in sorted(mix):\n lines.append(f\"- {key}: {mix[key]}\")\n lines.extend(\n [\n \"\",\n \"## Quality\",\n f\"- records: {payload['curated']['record_count']}\",\n f\"- benchmark_pass_rate: {payload['benchmark']['pass_rate']}\",\n f\"- foundry_quality: {payload['foundry']['quality']['passed']}\",\n f\"- bundle_verified: {payload['bundle_verify']['passed']}\",\n f\"- promotion_verified: {payload['promotion_verify']['passed']}\",\n f\"- review_verified: {payload['review_verify']['passed'] if payload['review_verify'] else 'not_reviewed'}\",\n f\"- release_index_verified: {payload['index_verify']['passed']}\",\n \"\",\n \"## Gates\",\n ]\n )\n for gate in lock.get(\"quality\", {}).get(\"quality_gates\", []):\n lines.append(f\"- {gate['name']}: {gate['passed']} ({gate['actual']} / {gate['threshold']})\")\n lines.extend(\n [\n \"\",\n \"## Anchors\",\n f\"- promotion_hash: {payload['promotion'].get('promotion_hash')}\",\n f\"- review_hash: {payload['review'].get('review_hash') if payload['review'] else 'not_reviewed'}\",\n f\"- release_index_hash: {payload['index'].get('release_index_hash')}\",\n \"\",\n ]\n )\n path.write_text(\"\\n\".join(lines), encoding=\"utf-8\")","instruction":"Explain the role of `def write_report_card(path: Path, **payload: Any) -> None` in Primitive Foundry.","output":"`write_report_card` is a function in `primitive_foundry.product_factory`. It belongs to the release, benchmark, product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.write_report_card","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.write_manifest_lock::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef write_manifest_lock(path: Path, payload: dict[str, Any]) -> dict[str, Any]:\n locked = {**payload, \"manifest_type\": \"aml_product_manifest_lock\", \"manifest_lock_hash\": \"\"}\n locked[\"manifest_lock_hash\"] = sha256_json(locked)\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(json.dumps(locked, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return locked","instruction":"Explain the role of `def write_manifest_lock(path: Path, payload: dict[str, Any]) -> dict[str, Any]` in Primitive Foundry.","output":"`write_manifest_lock` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.write_manifest_lock","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.verify_manifest_lock::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef verify_manifest_lock(path: str | Path) -> dict[str, Any]:\n lock_path = Path(path)\n lock = json.loads(lock_path.read_text(encoding=\"utf-8\"))\n expected = sha256_json({**lock, \"manifest_lock_hash\": \"\"})\n failures = []\n if lock.get(\"manifest_type\") != \"aml_product_manifest_lock\":\n failures.append(\"invalid_manifest_type\")\n if lock.get(\"manifest_lock_hash\") != expected:\n failures.append(\"manifest_lock_hash_mismatch\")\n current_hashes = artifact_hashes(lock.get(\"artifacts\", {}))\n if lock.get(\"hashes\") != current_hashes:\n failures.append(\"artifact_hash_mismatch\")\n return {\n \"passed\": not failures,\n \"manifest_lock\": str(lock_path),\n \"candidate_id\": lock.get(\"candidate_id\"),\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_manifest_lock(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_manifest_lock` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.verify_manifest_lock","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.artifact_hashes::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef artifact_hashes(artifacts: dict[str, Any]) -> dict[str, str | None]:\n hashes: dict[str, str | None] = {}\n for name, value in sorted(artifacts.items()):\n if not value:\n hashes[name] = None\n continue\n path = Path(value)\n if path.is_file():\n hashes[name] = sha256_bytes(path.read_bytes())\n elif path.is_dir():\n files = {\n str(item.relative_to(path)): sha256_bytes(item.read_bytes())\n for item in sorted(path.rglob(\"*\"))\n if item.is_file()\n }\n hashes[name] = sha256_json(files)\n else:\n hashes[name] = \"missing\"\n return hashes","instruction":"Explain the role of `def artifact_hashes(artifacts: dict[str, Any]) -> dict[str, str | None]` in Primitive Foundry.","output":"`artifact_hashes` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.artifact_hashes","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.update_product_catalog::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef update_product_catalog(\n path: Path,\n candidate_id: str,\n lock: dict[str, Any],\n promotion_verify: dict[str, Any],\n review_verify: dict[str, Any] | None,\n) -> dict[str, Any]:\n if path.exists():\n catalog = json.loads(path.read_text(encoding=\"utf-8\"))\n else:\n catalog = {\"manifest_type\": \"aml_product_catalog\", \"products\": []}\n products = [item for item in catalog.get(\"products\", []) if item.get(\"candidate_id\") != candidate_id]\n products.append(\n {\n \"candidate_id\": candidate_id,\n \"manifest_lock\": lock[\"artifacts\"][\"report_card\"].replace(\"REPORT_CARD.md\", \"MANIFEST.lock\"),\n \"report_card\": lock[\"artifacts\"][\"report_card\"],\n \"bundle_dir\": lock[\"artifacts\"][\"bundle_dir\"],\n \"product_mix\": lock[\"product_mix\"],\n \"promotion_verified\": promotion_verify[\"passed\"],\n \"review_verified\": review_verify[\"passed\"] if review_verify else False,\n \"manifest_lock_hash\": lock[\"manifest_lock_hash\"],\n }\n )\n catalog = {\n \"manifest_type\": \"aml_product_catalog\",\n \"updated_at\": datetime.now(timezone.utc).isoformat(),\n \"products\": sorted(products, key=lambda item: item[\"candidate_id\"]),\n }\n catalog[\"catalog_hash\"] = sha256_json({**catalog, \"catalog_hash\": \"\"})\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(json.dumps(catalog, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return catalog","instruction":"Explain the role of `def update_product_catalog(path: Path, candidate_id: str, lock: dict[str, Any], promotion_verify: dict[str, Any], review_verify: dict[str, Any] | None) -> dict[str, Any]` in Primitive Foundry.","output":"`update_product_catalog` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.update_product_catalog","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.product_mix_from_classifications::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef product_mix_from_classifications(classifications: list[ProductClassification]) -> dict[str, int]:\n mix = {kind: 0 for kind in PRODUCT_KINDS}\n mix.update({\"high\": 0, \"medium\": 0})\n for item in classifications:\n mix[item.product_kind] = mix.get(item.product_kind, 0) + 1\n if item.value_tier in {\"high\", \"medium\"}:\n mix[item.value_tier] = mix.get(item.value_tier, 0) + 1\n return {key: value for key, value in mix.items() if value}","instruction":"Explain the role of `def product_mix_from_classifications(classifications: list[ProductClassification]) -> dict[str, int]` in Primitive Foundry.","output":"`product_mix_from_classifications` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.product_mix_from_classifications","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.product_economics::explain","input":"Module: primitive_foundry.product_factory\nDomains: benchmark, product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef product_economics(\n accepted: list[tuple[ProductEvent, ProductClassification]],\n benchmark_pass_rate: float,\n) -> dict[str, Any]:\n classifications = [classification for _, classification in accepted]\n source_diversity = len({str(Path(event.source_path).expanduser()) for event, _ in accepted})\n kind_diversity = len({classification.product_kind for classification in classifications})\n avg_value = (\n sum(classification.value_score for classification in classifications) / len(classifications)\n if classifications\n else 0.0\n )\n uniqueness_score = min(1.0, source_diversity / max(1, len(accepted)))\n benchmark_difficulty = 0.5 + (0.15 * kind_diversity)\n packaging_readiness = 1.0 if benchmark_pass_rate >= 1.0 and accepted else 0.5\n estimated_buyer_value = round(\n (0.35 * avg_value)\n + (0.25 * uniqueness_score)\n + (0.2 * min(1.0, benchmark_difficulty))\n + (0.2 * packaging_readiness),\n 4,\n )\n return {\n \"estimated_buyer_value\": estimated_buyer_value,\n \"average_event_value\": round(avg_value, 4),\n \"uniqueness_score\": round(uniqueness_score, 4),\n \"source_diversity_score\": round(min(1.0, source_diversity / 3), 4),\n \"benchmark_difficulty_score\": round(min(1.0, benchmark_difficulty), 4),\n \"packaging_readiness\": round(packaging_readiness, 4),\n }","instruction":"Explain the role of `def product_economics(accepted: list[tuple[ProductEvent, ProductClassification]], benchmark_pass_rate: float) -> dict[str, Any]` in Primitive Foundry.","output":"`product_economics` is a function in `primitive_foundry.product_factory`. It belongs to the benchmark, product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.product_economics","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.evaluate_product_quality_gates::explain","input":"Module: primitive_foundry.product_factory\nDomains: sterilization, release, benchmark, product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef evaluate_product_quality_gates(\n accepted: list[tuple[ProductEvent, ProductClassification]],\n *,\n min_records: int,\n min_source_diversity: int,\n require_product_kinds: tuple[str, ...],\n benchmark_pass_rate: float | None,\n foundry_passed: bool | None,\n bundle_passed: bool | None,\n sterilization_passed: bool | None,\n promotion_passed: bool | None,\n review_passed: bool | None,\n release_index_passed: bool | None,\n) -> list[dict[str, Any]]:\n kinds = {classification.product_kind for _, classification in accepted}\n source_paths = {str(Path(event.source_path).expanduser()) for event, _ in accepted}\n return [\n {\n \"name\": \"minimum_records\",\n \"passed\": len(accepted) >= min_records,\n \"actual\": len(accepted),\n \"threshold\": min_records,\n },\n {\n \"name\": \"source_diversity\",\n \"passed\": len(source_paths) >= min_source_diversity,\n \"actual\": len(source_paths),\n \"threshold\": min_source_diversity,\n },\n {\n \"name\": \"required_product_kinds\",\n \"passed\": set(require_product_kinds).issubset(kinds),\n \"actual\": sorted(kinds),\n \"threshold\": sorted(require_product_kinds),\n },\n {\n \"name\": \"benchmark_pass_rate\",\n \"passed\": benchmark_pass_rate is None or benchmark_pass_rate >= 1.0,\n \"actual\": benchmark_pass_rate,\n \"threshold\": 1.0,\n },\n {\n \"name\": \"foundry_quality\",\n \"passed\": foundry_passed is None or foundry_passed,\n \"actual\": foundry_passed,\n \"threshold\": True,\n },\n {\n \"name\": \"bundle_quality\",\n \"passed\": bundle_passed is None or bundle_passed,\n \"actual\": bundle_passed,\n \"threshold\": True,\n },\n {\n \"name\": \"sterilization_quality\",\n \"passed\": sterilization_passed is None or sterilization_passed,\n \"actual\": sterilization_passed,\n \"threshold\": True,\n },\n {\n \"name\": \"promotion_quality\",\n \"passed\": promotion_passed is None or promotion_passed,\n \"actual\": promotion_passed,\n \"threshold\": True,\n },\n {\n \"name\": \"review_quality\",\n \"passed\": review_passed is None or review_passed,\n \"actual\": review_passed,\n \"threshold\": True,\n },\n {\n \"name\": \"release_index_quality\",\n \"passed\": release_index_passed is None or release_index_passed,\n \"actual\": release_index_passed,\n \"threshold\": True,\n },\n ]","instruction":"Explain the role of `def evaluate_product_quality_gates(accepted: list[tuple[ProductEvent, ProductClassification]], *, min_records: int, min_source_diversity: int, require_product_kinds: tuple[str, ...], benchmark_pass_rate: float | None, foundry_passed: bool | None, bundle_passed: bool | None, sterilization_passed: bool | None, promotion_passed: bool | None, review_passed: bool | None, release_index_passed: bool | None) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`evaluate_product_quality_gates` is a function in `primitive_foundry.product_factory`. It belongs to the sterilization, release, benchmark, product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.evaluate_product_quality_gates","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.event_fingerprint::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef event_fingerprint(event: ProductEvent) -> set[str]:\n tokens = set()\n text = \" \".join([event.text, \" \".join(event.tags)]).lower().replace(\"-\", \" \")\n for token in text.split():\n cleaned = \"\".join(char for char in token if char.isalnum())\n if len(cleaned) >= 4:\n tokens.add(cleaned)\n return tokens","instruction":"Explain the role of `def event_fingerprint(event: ProductEvent) -> set[str]` in Primitive Foundry.","output":"`event_fingerprint` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.event_fingerprint","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.keyword_score::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef keyword_score(text: str, keywords: tuple[str, ...]) -> int:\n return sum(1 for keyword in keywords if keyword in text)","instruction":"Explain the role of `def keyword_score(text: str, keywords: tuple[str, ...]) -> int` in Primitive Foundry.","output":"`keyword_score` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.keyword_score","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.matched_keywords::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef matched_keywords(text: str, keywords: tuple[str, ...]) -> list[str]:\n return [keyword for keyword in keywords if keyword in text]","instruction":"Explain the role of `def matched_keywords(text: str, keywords: tuple[str, ...]) -> list[str]` in Primitive Foundry.","output":"`matched_keywords` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.matched_keywords","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.asdict_classification::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef asdict_classification(classification: ProductClassification) -> dict[str, Any]:\n return {\n \"event_id\": classification.event_id,\n \"product_kind\": classification.product_kind,\n \"domain_path\": classification.domain_path,\n \"value_tier\": classification.value_tier,\n \"value_score\": classification.value_score,\n \"accepted\": classification.accepted,\n \"reasons\": classification.reasons,\n }","instruction":"Explain the role of `def asdict_classification(classification: ProductClassification) -> dict[str, Any]` in Primitive Foundry.","output":"`asdict_classification` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.asdict_classification","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.append_jsonl::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef append_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"a\", encoding=\"utf-8\") as handle:\n for row in rows:\n handle.write(json.dumps(row, sort_keys=True))\n handle.write(\"\\n\")","instruction":"Explain the role of `def append_jsonl(path: Path, rows: list[dict[str, Any]]) -> None` in Primitive Foundry.","output":"`append_jsonl` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.append_jsonl","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_factory.write_quarantine_event::explain","input":"Module: primitive_foundry.product_factory\nDomains: product_factory\nSource path: primitive_foundry/product_factory.py\n\ndef write_quarantine_event(\n quarantine_dir: Path,\n event: ProductEvent,\n reason: str,\n classification: ProductClassification,\n) -> None:\n quarantine_dir.mkdir(parents=True, exist_ok=True)\n payload = {\n \"manifest_type\": \"aml_quarantine_event\",\n \"event_id\": event.event_id,\n \"reason\": reason,\n \"classification\": asdict_classification(classification),\n \"source_path\": event.source_path,\n \"tags\": event.tags,\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n }\n payload[\"quarantine_hash\"] = sha256_json({**payload, \"quarantine_hash\": \"\"})\n (quarantine_dir / f\"{event.event_id}.json\").write_text(\n json.dumps(payload, indent=2, sort_keys=True) + \"\\n\",\n encoding=\"utf-8\",\n )","instruction":"Explain the role of `def write_quarantine_event(quarantine_dir: Path, event: ProductEvent, reason: str, classification: ProductClassification) -> None` in Primitive Foundry.","output":"`write_quarantine_event` is a function in `primitive_foundry.product_factory`. It belongs to the product_factory area of Primitive Foundry.","source_id":"primitive_foundry.product_factory.write_quarantine_event","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_families.agent_runtime_governance.generate_agent_runtime_governance_card::explain","input":"Module: primitive_foundry.product_families.agent_runtime_governance\nDomains: foundry\nSource path: primitive_foundry/product_families/agent_runtime_governance.py\n\ndef generate_agent_runtime_governance_card(\n *,\n base: dict[str, Any],\n domain_path: str,\n sterile_text: str,\n reviewer: str,\n) -> dict[str, Any]:\n cells = expected_cells(\"energy.grid\", include_embedding=True)\n return {\n **base,\n \"source_family\": FAMILY,\n \"task\": \"runtime_governance_trace\",\n \"domain_path\": \"energy.grid\",\n \"query\": (\n \"Score an agent runtime governance trace for an energy grid planning task. \"\n \"The agent reaches an authority decision point: scheduler override, model escalation, \"\n \"or human-approval gate. It must preserve the governance rule before continuing. \"\n f\"Source: {sterile_text}\"\n ),\n \"expected_answer\": \" + \".join(cells),\n \"expected_cell_id\": cells[0],\n \"expected_cell_ids\": cells,\n \"stale_cell_id\": \"energy.grid.2023\",\n \"replacement_for\": \"energy.grid.2023\",\n \"rubric\": {\n \"type\": \"trace\",\n \"required_trace_events\": [\n \"task_received\",\n \"authority_decision_point_detected\",\n \"governance_rule_checked\",\n \"approval_or_escalation_recorded\",\n \"action_continued_or_blocked\",\n ],\n \"pass_conditions\": [\"rule_honored\", \"trace_complete\", \"no_silent_override\"],\n },\n \"domain_review\": base_review(reviewer),\n \"buyer_task\": {\n \"family\": FAMILY,\n \"inputs\": [\"task_trace\", \"governance_policy\", \"authority_gate\"],\n \"expected_output\": \"scored coordination trace with pass/fail governance decision\",\n },\n \"metadata\": {\"authority_points\": [\"model_escalation\", \"scheduler_override\", \"human_approval_gate\"]},\n }","instruction":"Explain the role of `def generate_agent_runtime_governance_card(*, base: dict[str, Any], domain_path: str, sterile_text: str, reviewer: str) -> dict[str, Any]` in Primitive Foundry.","output":"`generate_agent_runtime_governance_card` is a function in `primitive_foundry.product_families.agent_runtime_governance`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.product_families.agent_runtime_governance.generate_agent_runtime_governance_card","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_families.common.base_review::explain","input":"Module: primitive_foundry.product_families.common\nDomains: foundry\nSource path: primitive_foundry/product_families/common.py\n\ndef base_review(reviewer: str | None = None) -> dict[str, Any]:\n review = dict(FOUNDER_DOMAIN_REVIEW)\n if reviewer:\n review[\"reviewer_name\"] = reviewer\n return review","instruction":"Explain the role of `def base_review(reviewer: str | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`base_review` is a function in `primitive_foundry.product_families.common`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.product_families.common.base_review","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_families.common.expected_cells::explain","input":"Module: primitive_foundry.product_families.common\nDomains: foundry\nSource path: primitive_foundry/product_families/common.py\n\ndef expected_cells(domain_path: str, include_embedding: bool = False) -> list[str]:\n cells = [f\"{domain_path}.2024\"]\n if include_embedding and domain_path != \"technology.embedding\":\n cells.append(\"technology.embedding.2024\")\n return cells","instruction":"Explain the role of `def expected_cells(domain_path: str, include_embedding: bool=False) -> list[str]` in Primitive Foundry.","output":"`expected_cells` is a function in `primitive_foundry.product_families.common`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.product_families.common.expected_cells","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.run_product_planner_once::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner, curation\nSource path: primitive_foundry/product_planner.py\n\ndef run_product_planner_once(\n *,\n events_path: str | Path,\n output_root: str | Path = artifact_path(\"products\", \"autonomous\"),\n state_path: str | Path | None = None,\n target_size: str = \"standard\",\n target_count: int | None = None,\n min_value_score: float = MEDIUM_VALUE_THRESHOLD,\n min_source_diversity: int = 3,\n classifier: str = \"deterministic\",\n dedupe_threshold: float = 0.92,\n reviewer: str = \"local-autonomous-reviewer\",\n delivery_shapes: tuple[str, ...] = (\"tar_gz\",),\n standing_orders_path: str | Path | None = None,\n curation_plan_path: str | Path | None = None,\n) -> dict[str, Any]:\n target = resolve_target_count(target_size, target_count)\n root = Path(output_root)\n queues_root = root / \"queues\"\n releases_root = root / \"releases\"\n packages_root = root / \"packages\"\n quarantine_root = root / \"quarantine\"\n for directory in (queues_root, releases_root, packages_root, quarantine_root):\n directory.mkdir(parents=True, exist_ok=True)\n\n state_file = Path(state_path) if state_path else root / \"PRODUCT_PLANNER_STATE.json\"\n state = load_planner_state(state_file)\n processed_ids = set(state.get(\"processed_event_ids\", []))\n queue_counts_before = queue_counts(queues_root)\n\n rows = read_product_event_rows(events_path)\n routed_count = 0\n rejected_count = 0\n duplicate_count = 0\n invalid_count = 0\n deferred_count = 0\n\n queue_fingerprints = load_queue_fingerprints(queues_root)\n for row in rows:\n if row.event is None:\n invalid_count += 1\n continue\n event = row.event\n if event.event_id in processed_ids:\n duplicate_count += 1\n continue\n classification = classify_event_with_mode(event, min_value_score, classifier)\n if not classification.accepted:\n rejected_count += 1\n processed_ids.add(event.event_id)\n write_quarantine_event(quarantine_root, event, \"below_value_threshold\", classification)\n continue\n family = classify_product_family(event, classification)\n fingerprint = event_fingerprint(event)\n duplicate_of = semantic_duplicate_index(fingerprint, queue_fingerprints.setdefault(family, []), dedupe_threshold)\n if duplicate_of is not None:\n rejected_count += 1\n processed_ids.add(event.event_id)\n write_quarantine_event(quarantine_root, event, \"semantic_duplicate\", classification)\n continue\n append_queue_event(queues_root / f\"{family}.jsonl\", event, classification, family)\n queue_fingerprints[family].append(fingerprint)\n processed_ids.add(event.event_id)\n routed_count += 1\n\n releases = []\n for family in PRODUCT_FAMILIES:\n queue_path = queues_root / f\"{family}.jsonl\"\n queued = read_queue_events(queue_path)\n if len(queued) < target:\n continue\n if source_diversity(queued[:target]) < min_source_diversity:\n deferred_count += len(queued)\n continue\n release = close_product_queue(\n family=family,\n queue_path=queue_path,\n queued=queued,\n target=target,\n releases_root=releases_root,\n packages_root=packages_root,\n state=state,\n target_size=target_size,\n min_value_score=min_value_score,\n min_source_diversity=min_source_diversity,\n classifier=classifier,\n reviewer=reviewer,\n delivery_shapes=delivery_shapes,\n )\n releases.append(release)\n\n state[\"processed_event_ids\"] = sorted(processed_ids)\n state[\"updated_at\"] = datetime.now(timezone.utc).isoformat()\n state[\"events_path\"] = str(events_path)\n state[\"target_size\"] = target_size\n state[\"target_count\"] = target\n state[\"classifier\"] = classifier\n save_planner_state(state_file, state)\n curation_plan = plan_curation(\n events_path=events_path,\n standing_orders_path=standing_orders_path,\n output_path=curation_plan_path,\n min_value_score=min_value_score,\n classifier=classifier,\n )\n return {\n \"planner\": \"aml_product_planner\",\n \"passed\": all(release[\"passed\"] for release in releases),\n \"events_path\": str(events_path),\n \"output_root\": str(root),\n \"state_path\": str(state_file),\n \"target_size\": target_size,\n \"target_count\": target,\n \"routed_count\": routed_count,\n \"rejected_count\": rejected_count,\n \"duplicate_count\": duplicate_count,\n \"invalid_count\": invalid_count,\n \"deferred_count\": deferred_count,\n \"queue_counts_before\": queue_counts_before,\n \"queue_counts_after\": queue_counts(queues_root),\n \"releases_created\": len(releases),\n \"releases\": releases,\n \"curation_plan\": curation_plan,\n \"curation_event\": build_curation_plan_event(curation_plan),\n }","instruction":"Explain the role of `def run_product_planner_once(*, events_path: str | Path, output_root: str | Path=artifact_path('products', 'autonomous'), state_path: str | Path | None=None, target_size: str='standard', target_count: int | None=None, min_value_score: float=MEDIUM_VALUE_THRESHOLD, min_source_diversity: int=3, classifier: str='deterministic', dedupe_threshold: float=0.92, reviewer: str='local-autonomous-reviewer', delivery_shapes: tuple[str, ...]=('tar_gz',), standing_orders_path: str | Path | None=None, curation_plan_path: str | Path | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`run_product_planner_once` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner, curation area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.run_product_planner_once","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.run_product_node::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner, curation\nSource path: primitive_foundry/product_planner.py\n\ndef run_product_node(\n *,\n events_path: str | Path,\n output_root: str | Path = artifact_path(\"products\", \"autonomous\"),\n state_path: str | Path | None = None,\n target_size: str = \"standard\",\n target_count: int | None = None,\n min_value_score: float = MEDIUM_VALUE_THRESHOLD,\n min_source_diversity: int = 3,\n classifier: str = \"deterministic\",\n dedupe_threshold: float = 0.92,\n reviewer: str = \"local-autonomous-reviewer\",\n iterations: int = 1,\n poll_seconds: float = 5.0,\n delivery_shapes: tuple[str, ...] = (\"tar_gz\",),\n standing_orders_path: str | Path | None = None,\n curation_plan_path: str | Path | None = None,\n) -> dict[str, Any]:\n if iterations < 0:\n raise ValueError(\"iterations must be >= 0\")\n results = []\n count = 0\n while True:\n results.append(\n run_product_planner_once(\n events_path=events_path,\n output_root=output_root,\n state_path=state_path,\n target_size=target_size,\n target_count=target_count,\n min_value_score=min_value_score,\n min_source_diversity=min_source_diversity,\n classifier=classifier,\n dedupe_threshold=dedupe_threshold,\n reviewer=reviewer,\n delivery_shapes=delivery_shapes,\n standing_orders_path=standing_orders_path,\n curation_plan_path=curation_plan_path,\n )\n )\n count += 1\n if iterations and count >= iterations:\n break\n if iterations == 0 or count < iterations:\n time.sleep(poll_seconds)\n return {\n \"planner\": \"aml_product_planner\",\n \"iterations\": len(results),\n \"releases_created\": sum(item[\"releases_created\"] for item in results),\n \"results\": results,\n \"passed\": all(item[\"passed\"] for item in results),\n }","instruction":"Explain the role of `def run_product_node(*, events_path: str | Path, output_root: str | Path=artifact_path('products', 'autonomous'), state_path: str | Path | None=None, target_size: str='standard', target_count: int | None=None, min_value_score: float=MEDIUM_VALUE_THRESHOLD, min_source_diversity: int=3, classifier: str='deterministic', dedupe_threshold: float=0.92, reviewer: str='local-autonomous-reviewer', iterations: int=1, poll_seconds: float=5.0, delivery_shapes: tuple[str, ...]=('tar_gz',), standing_orders_path: str | Path | None=None, curation_plan_path: str | Path | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`run_product_node` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner, curation area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.run_product_node","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.close_product_queue::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, commercial, planner\nSource path: primitive_foundry/product_planner.py\n\ndef close_product_queue(\n *,\n family: str,\n queue_path: Path,\n queued: list[dict[str, Any]],\n target: int,\n releases_root: Path,\n packages_root: Path,\n state: dict[str, Any],\n target_size: str,\n min_value_score: float,\n min_source_diversity: int,\n classifier: str,\n reviewer: str,\n delivery_shapes: tuple[str, ...],\n) -> dict[str, Any]:\n sequence = int(state.setdefault(\"family_sequences\", {}).get(family, 0)) + 1\n release_id = f\"{family}_{sequence:06d}\"\n release_events = queued[:target]\n remaining_events = queued[target:]\n release_dir = releases_root / release_id\n assert_release_id_immutable(release_dir)\n release_dir.mkdir(parents=True, exist_ok=True)\n release_events_path = release_dir / \"events.jsonl\"\n write_jsonl(release_events_path, [item[\"event\"] for item in release_events])\n write_jsonl(queue_path, remaining_events)\n\n required_kinds = REQUIRED_KIND_BY_FAMILY.get(family, ())\n candidate = build_candidate_from_events(\n events_path=release_events_path,\n output_root=releases_root,\n candidate_id=release_id,\n min_value_score=min_value_score,\n reviewer=reviewer,\n approve=True,\n min_records=target,\n min_source_diversity=min_source_diversity,\n require_product_kinds=required_kinds,\n classifier=classifier,\n )\n commercial = write_commercial_artifacts(\n release_dir=releases_root / release_id,\n release_id=release_id,\n family=family,\n target_size=target_size,\n target_count=target,\n record_count=len(release_events),\n source_diversity=source_diversity(release_events),\n candidate=candidate,\n )\n commercial_verify = verify_commercial_release(releases_root / release_id)\n build_buyer_preview(releases_root / release_id, preview_records=min(10, len(release_events)))\n repair_product_manifest_lock(releases_root / release_id)\n delivery = write_delivery_shapes(releases_root / release_id, list(delivery_shapes))\n delivery_verify = verify_delivery_shapes(releases_root / release_id, list(delivery_shapes))\n aws_package = write_aws_data_exchange_package(release_dir=releases_root / release_id)\n aws_package_verify = verify_aws_data_exchange_package(aws_package[\"package_dir\"])\n package = package_product(candidate_dir=releases_root / release_id, output_dir=packages_root)\n package_verify = verify_package(package[\"manifest\"])\n lock_hash = manifest_lock_hash(release_dir / \"MANIFEST.lock\")\n claim_release_id(release_dir, lock_hash=lock_hash)\n manifest = {\n \"manifest_type\": \"aml_autonomous_product_release\",\n \"release_id\": release_id,\n \"family\": family,\n \"target_size\": target_size,\n \"target_count\": target,\n \"record_count\": len(release_events),\n \"source_diversity\": source_diversity(release_events),\n \"candidate\": candidate,\n \"commercial\": commercial,\n \"commercial_verify\": commercial_verify,\n \"delivery\": delivery,\n \"delivery_verify\": delivery_verify,\n \"package\": package,\n \"package_verify\": package_verify,\n \"aws_data_exchange\": aws_package,\n \"aws_data_exchange_verify\": aws_package_verify,\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"next_queue_count\": len(remaining_events),\n }\n manifest[\"release_hash\"] = sha256_json({**manifest, \"release_hash\": \"\"})\n manifest_path = release_dir / \"AUTONOMOUS_RELEASE.json\"\n manifest_path.write_text(json.dumps(manifest, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n state[\"family_sequences\"][family] = sequence\n state.setdefault(\"releases\", []).append(\n {\n \"release_id\": release_id,\n \"family\": family,\n \"manifest\": str(manifest_path),\n \"package\": package[\"package\"],\n \"created_at\": manifest[\"created_at\"],\n }\n )\n return {\n \"release_id\": release_id,\n \"family\": family,\n \"manifest\": str(manifest_path),\n \"candidate_dir\": str(releases_root / release_id),\n \"package\": package[\"package\"],\n \"passed\": (\n candidate[\"passed\"]\n and commercial_verify[\"passed\"]\n and delivery_verify[\"passed\"]\n and package_verify[\"passed\"]\n and aws_package_verify[\"passed\"]\n ),\n }","instruction":"Explain the role of `def close_product_queue(*, family: str, queue_path: Path, queued: list[dict[str, Any]], target: int, releases_root: Path, packages_root: Path, state: dict[str, Any], target_size: str, min_value_score: float, min_source_diversity: int, classifier: str, reviewer: str, delivery_shapes: tuple[str, ...]) -> dict[str, Any]` in Primitive Foundry.","output":"`close_product_queue` is a function in `primitive_foundry.product_planner`. It belongs to the release, commercial, planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.close_product_queue","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.classify_product_family::explain","input":"Module: primitive_foundry.product_planner\nDomains: sterilization, privacy, marketplace, license, planner, dataset, router, benchmark\nSource path: primitive_foundry/product_planner.py\n\ndef classify_product_family(event: ProductEvent, classification: ProductClassification) -> str:\n text = \" \".join([event.text, \" \".join(event.tags), json.dumps(event.metadata, sort_keys=True)]).lower()\n for tag in event.tags:\n if tag in FAMILY_REGISTRY and not FAMILY_REGISTRY[tag].legacy and tag not in {\"dataset\", \"eval_harness\", \"benchmark\"}:\n return tag\n metadata_family = event.metadata.get(\"dataset_family\") or event.metadata.get(\"source_family\") or event.metadata.get(\"planner_family\")\n if metadata_family in FAMILY_REGISTRY and not FAMILY_REGISTRY[metadata_family].legacy:\n return str(metadata_family)\n if any(token in text for token in (\"privacy\", \"provenance\", \"sterilization\", \"license\")):\n return \"privacy_provenance_eval\"\n if any(token in text for token in (\"agent\", \"trace\", \"trajectory\", \"tool call\", \"governance\", \"override\")):\n return \"agent_runtime_governance\"\n if any(token in text for token in (\"lifecycle\", \"apoptosis\", \"replacement\", \"stale\", \"retired\", \"repair\")):\n return \"verified_agentic_build\"\n if any(token in text for token in (\"router\", \"embedding\", \"nomic\", \"classifier\", \"training\")):\n return \"router_training\"\n if any(token in text for token in (\"marketplace\", \"buyer\", \"sale\", \"pricing\", \"commerce\")):\n return \"marketplace_bundle\"\n return classification.product_kind","instruction":"Explain the role of `def classify_product_family(event: ProductEvent, classification: ProductClassification) -> str` in Primitive Foundry.","output":"`classify_product_family` is a function in `primitive_foundry.product_planner`. It belongs to the sterilization, privacy, marketplace, license, planner, dataset, router, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.classify_product_family","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.assert_release_id_immutable::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner\nSource path: primitive_foundry/product_planner.py\n\ndef assert_release_id_immutable(release_dir: Path, expected_lock_hash: str | None = None) -> None:\n ledger = load_release_ledger(release_dir.parent)\n ledger_entry = ledger.get(\"releases\", {}).get(release_dir.name)\n if ledger_entry and ledger_entry.get(\"claimed\") is True:\n claimed_hash = str(ledger_entry.get(\"lock_hash\") or \"\")\n if expected_lock_hash is None or claimed_hash != expected_lock_hash:\n raise RuntimeError(f\"ReleaseImmutabilityViolation:{release_dir.name}\")\n lock_path = release_dir / \"MANIFEST.lock\"\n if not lock_path.exists():\n return\n if expected_lock_hash is None:\n raise RuntimeError(f\"ReleaseImmutabilityViolation:{release_dir.name}\")\n current = manifest_lock_hash(lock_path)\n if current != expected_lock_hash:\n raise RuntimeError(f\"ReleaseImmutabilityViolation:{release_dir.name}\")","instruction":"Explain the role of `def assert_release_id_immutable(release_dir: Path, expected_lock_hash: str | None=None) -> None` in Primitive Foundry.","output":"`assert_release_id_immutable` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.assert_release_id_immutable","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.claim_release_id::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner, atomic_write\nSource path: primitive_foundry/product_planner.py\n\ndef claim_release_id(release_dir: Path, lock_hash: str) -> dict[str, Any]:\n ledger_path = release_ledger_path(release_dir.parent)\n ledger = load_release_ledger(release_dir.parent)\n releases = ledger.setdefault(\"releases\", {})\n existing = releases.get(release_dir.name)\n if existing and existing.get(\"claimed\") is True and existing.get(\"lock_hash\") != lock_hash:\n raise RuntimeError(f\"ReleaseImmutabilityViolation:{release_dir.name}\")\n releases[release_dir.name] = {\n \"release_id\": release_dir.name,\n \"claimed\": True,\n \"lock_hash\": lock_hash,\n \"release_dir\": str(release_dir),\n }\n ledger[\"ledger_hash\"] = sha256_json({**ledger, \"ledger_hash\": \"\"})\n locked_atomic_write_json(ledger_path, ledger)\n return ledger","instruction":"Explain the role of `def claim_release_id(release_dir: Path, lock_hash: str) -> dict[str, Any]` in Primitive Foundry.","output":"`claim_release_id` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.claim_release_id","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.load_release_ledger::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner\nSource path: primitive_foundry/product_planner.py\n\ndef load_release_ledger(releases_root: Path) -> dict[str, Any]:\n ledger_path = release_ledger_path(releases_root)\n if not ledger_path.exists():\n return {\n \"ledger_type\": \"primitive_foundry_release_ledger\",\n \"schema_version\": 1,\n \"releases\": {},\n \"ledger_hash\": \"\",\n }\n ledger = json.loads(ledger_path.read_text(encoding=\"utf-8\"))\n if \"releases\" not in ledger or not isinstance(ledger[\"releases\"], dict):\n ledger[\"releases\"] = {}\n return ledger","instruction":"Explain the role of `def load_release_ledger(releases_root: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`load_release_ledger` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.load_release_ledger","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.release_ledger_path::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner\nSource path: primitive_foundry/product_planner.py\n\ndef release_ledger_path(releases_root: Path) -> Path:\n return Path(releases_root) / \"RELEASE_LEDGER.json\"","instruction":"Explain the role of `def release_ledger_path(releases_root: Path) -> Path` in Primitive Foundry.","output":"`release_ledger_path` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.release_ledger_path","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.classify_source_card::explain","input":"Module: primitive_foundry.product_planner\nDomains: privacy, planner, dataset, source_card\nSource path: primitive_foundry/product_planner.py\n\ndef classify_source_card(card: dict[str, Any]) -> str:\n tags = [str(tag) for tag in card.get(\"tags\", [])]\n for tag in tags:\n if tag in FAMILY_REGISTRY and not FAMILY_REGISTRY[tag].legacy:\n return tag\n explicit_family = str(card.get(\"source_family\") or \"\")\n if explicit_family in FAMILY_REGISTRY and not FAMILY_REGISTRY[explicit_family].legacy:\n return explicit_family\n metadata = card.get(\"metadata\", {})\n if isinstance(metadata, dict):\n adapter = str(metadata.get(\"origin_adapter\") or metadata.get(\"adapter\") or \"\")\n if adapter in ADAPTER_TO_FAMILY:\n return ADAPTER_TO_FAMILY[adapter]\n text = \" \".join(\n [\n str(card.get(\"query\", \"\")),\n str(card.get(\"source_summary\", \"\")),\n \" \".join(tags),\n json.dumps(metadata, sort_keys=True) if isinstance(metadata, dict) else str(metadata),\n ]\n ).lower()\n if any(token in text for token in (\"privacy\", \"provenance\", \"gdpr\", \"ccpa\", \"hipaa\", \"eu_ai_act\")):\n return \"privacy_provenance_eval\"\n if any(token in text for token in (\"governance\", \"override\", \"scheduler\", \"escalation\", \"authority\")):\n return \"agent_runtime_governance\"\n if any(token in text for token in (\"build\", \"patch\", \"repair\", \"test suite\", \"scaffold\")):\n return \"verified_agentic_build\"\n return \"dataset\"","instruction":"Explain the role of `def classify_source_card(card: dict[str, Any]) -> str` in Primitive Foundry.","output":"`classify_source_card` is a function in `primitive_foundry.product_planner`. It belongs to the privacy, planner, dataset, source_card area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.classify_source_card","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.read_queue_events::explain","input":"Module: primitive_foundry.product_planner\nDomains: planner\nSource path: primitive_foundry/product_planner.py\n\ndef read_queue_events(path: Path) -> list[dict[str, Any]]:\n if not path.exists():\n return []\n rows = []\n with path.open(\"r\", encoding=\"utf-8\") as handle:\n for line in handle:\n stripped = line.strip()\n if stripped:\n rows.append(json.loads(stripped))\n return rows","instruction":"Explain the role of `def read_queue_events(path: Path) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`read_queue_events` is a function in `primitive_foundry.product_planner`. It belongs to the planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.read_queue_events","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.load_queue_fingerprints::explain","input":"Module: primitive_foundry.product_planner\nDomains: planner\nSource path: primitive_foundry/product_planner.py\n\ndef load_queue_fingerprints(queues_root: Path) -> dict[str, list[set[str]]]:\n fingerprints: dict[str, list[set[str]]] = {}\n for family in PRODUCT_FAMILIES:\n fingerprints[family] = []\n for row in read_queue_events(queues_root / f\"{family}.jsonl\"):\n event = ProductEvent.from_dict(row[\"event\"], 0)\n fingerprints[family].append(event_fingerprint(event))\n return fingerprints","instruction":"Explain the role of `def load_queue_fingerprints(queues_root: Path) -> dict[str, list[set[str]]]` in Primitive Foundry.","output":"`load_queue_fingerprints` is a function in `primitive_foundry.product_planner`. It belongs to the planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.load_queue_fingerprints","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.queue_counts::explain","input":"Module: primitive_foundry.product_planner\nDomains: planner\nSource path: primitive_foundry/product_planner.py\n\ndef queue_counts(queues_root: Path) -> dict[str, int]:\n return {family: len(read_queue_events(queues_root / f\"{family}.jsonl\")) for family in PRODUCT_FAMILIES}","instruction":"Explain the role of `def queue_counts(queues_root: Path) -> dict[str, int]` in Primitive Foundry.","output":"`queue_counts` is a function in `primitive_foundry.product_planner`. It belongs to the planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.queue_counts","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.source_diversity::explain","input":"Module: primitive_foundry.product_planner\nDomains: planner\nSource path: primitive_foundry/product_planner.py\n\ndef source_diversity(rows: list[dict[str, Any]]) -> int:\n return len({str(Path(row[\"event\"][\"source_path\"]).expanduser()) for row in rows})","instruction":"Explain the role of `def source_diversity(rows: list[dict[str, Any]]) -> int` in Primitive Foundry.","output":"`source_diversity` is a function in `primitive_foundry.product_planner`. It belongs to the planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.source_diversity","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.resolve_target_count::explain","input":"Module: primitive_foundry.product_planner\nDomains: planner\nSource path: primitive_foundry/product_planner.py\n\ndef resolve_target_count(target_size: str, target_count: int | None) -> int:\n if target_count is not None:\n if target_count < 1:\n raise ValueError(\"target_count must be >= 1\")\n return target_count\n if target_size not in STANDARD_PRODUCT_SIZES:\n raise ValueError(f\"Unsupported target_size: {target_size}\")\n return STANDARD_PRODUCT_SIZES[target_size]","instruction":"Explain the role of `def resolve_target_count(target_size: str, target_count: int | None) -> int` in Primitive Foundry.","output":"`resolve_target_count` is a function in `primitive_foundry.product_planner`. It belongs to the planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.resolve_target_count","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.load_planner_state::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner\nSource path: primitive_foundry/product_planner.py\n\ndef load_planner_state(path: Path) -> dict[str, Any]:\n if not path.exists():\n return {\n \"manifest_type\": \"aml_product_planner_state\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"updated_at\": None,\n \"processed_event_ids\": [],\n \"family_sequences\": {},\n \"releases\": [],\n }\n state = json.loads(path.read_text(encoding=\"utf-8\"))\n if state.get(\"manifest_type\") != \"aml_product_planner_state\":\n raise ValueError(f\"Invalid product planner state: {path}\")\n return state","instruction":"Explain the role of `def load_planner_state(path: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`load_planner_state` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.load_planner_state","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.save_planner_state::explain","input":"Module: primitive_foundry.product_planner\nDomains: planner, atomic_write\nSource path: primitive_foundry/product_planner.py\n\ndef save_planner_state(path: Path, state: dict[str, Any]) -> None:\n payload = {**state, \"state_hash\": \"\"}\n payload[\"state_hash\"] = sha256_json(payload)\n locked_atomic_write_json(path, payload)","instruction":"Explain the role of `def save_planner_state(path: Path, state: dict[str, Any]) -> None` in Primitive Foundry.","output":"`save_planner_state` is a function in `primitive_foundry.product_planner`. It belongs to the planner, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.save_planner_state","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.verify_planner_state::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner\nSource path: primitive_foundry/product_planner.py\n\ndef verify_planner_state(path: str | Path) -> dict[str, Any]:\n state_path = Path(path)\n state = json.loads(state_path.read_text(encoding=\"utf-8\"))\n failures = []\n if state.get(\"manifest_type\") != \"aml_product_planner_state\":\n failures.append(\"invalid_manifest_type\")\n if state.get(\"state_hash\") != sha256_json({**state, \"state_hash\": \"\"}):\n failures.append(\"state_hash_mismatch\")\n ids = list(state.get(\"processed_event_ids\", []))\n if len(ids) != len(set(ids)):\n failures.append(\"duplicate_processed_event_ids\")\n return {\n \"passed\": not failures,\n \"state_path\": str(state_path),\n \"processed_event_count\": len(ids),\n \"release_count\": len(state.get(\"releases\", [])),\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_planner_state(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_planner_state` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.verify_planner_state","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.verify_autonomous_release::explain","input":"Module: primitive_foundry.product_planner\nDomains: sterilization, release, marketplace, commercial, planner\nSource path: primitive_foundry/product_planner.py\n\ndef verify_autonomous_release(path: str | Path) -> dict[str, Any]:\n manifest_path = Path(path)\n manifest = json.loads(manifest_path.read_text(encoding=\"utf-8\"))\n failures = []\n if manifest.get(\"manifest_type\") != \"aml_autonomous_product_release\":\n failures.append(\"invalid_manifest_type\")\n if manifest.get(\"release_hash\") != sha256_json({**manifest, \"release_hash\": \"\"}):\n failures.append(\"release_hash_mismatch\")\n release_dir = manifest_path.parent\n release_id = str(manifest.get(\"release_id\") or \"\")\n if not release_id:\n failures.append(\"missing_release_id\")\n elif release_dir.name != release_id:\n failures.append(\"release_dir_id_mismatch\")\n candidate = manifest.get(\"candidate\", {})\n if str(candidate.get(\"candidate_id\") or \"\") != release_id:\n failures.append(\"candidate_id_mismatch\")\n if candidate.get(\"candidate_dir\") and Path(candidate[\"candidate_dir\"]) != release_dir:\n failures.append(\"candidate_dir_mismatch\")\n required_files = [\n \"events.jsonl\",\n \"MANIFEST.lock\",\n \"REPORT_CARD.md\",\n \"AUTONOMOUS_RELEASE.json\",\n \"MARKETPLACE_LISTING.json\",\n \"COMMERCIAL_READINESS.json\",\n \"TERMS.md\",\n \"MARKETPLACE_METADATA.json\",\n \"MARKETPLACE_CHANNEL_PLAN.json\",\n \"BUYER_SAMPLE_POLICY.json\",\n \"VERSION_POLICY.json\",\n \"PRICING_EVIDENCE.json\",\n \"LEGAL_REVIEW_PACKET.json\",\n \"aws_data_exchange/AWS_DATA_EXCHANGE_POSTING.json\",\n \"aws_data_exchange/aws_listing_fields.json\",\n \"aws_data_exchange/aws_upload_manifest.json\",\n \"aws_data_exchange/DATA_SUBSCRIPTION_AGREEMENT.md\",\n \"bundle/README.md\",\n ]\n for relative in required_files:\n if not (release_dir / relative).exists():\n failures.append(f\"missing:{relative}\")\n lock_path = release_dir / \"MANIFEST.lock\"\n if lock_path.exists():\n lock_verify = verify_manifest_lock(lock_path)\n if not lock_verify[\"passed\"]:\n failures.append(\"manifest_lock_failed\")\n else:\n lock_verify = {\"passed\": False, \"failures\": [\"missing\"]}\n package_info = manifest.get(\"package\", {})\n package_manifest = package_info.get(\"manifest\")\n if package_manifest:\n package_verify = verify_package(package_manifest)\n if not package_verify[\"passed\"]:\n failures.append(\"package_failed\")\n package_manifest_path = Path(package_manifest)\n package_path = Path(package_info.get(\"package\", \"\"))\n expected_packages_root = release_dir.parent.parent / \"packages\"\n if package_manifest_path.parent != expected_packages_root:\n failures.append(\"package_manifest_root_mismatch\")\n if package_path.parent != expected_packages_root:\n failures.append(\"package_root_mismatch\")\n if package_manifest_path.name != f\"{release_id}.package.json\":\n failures.append(\"package_manifest_name_mismatch\")\n if package_path.name != f\"{release_id}.tar.gz\":\n failures.append(\"package_name_mismatch\")\n if package_verify.get(\"candidate_id\") != release_id:\n failures.append(\"package_candidate_id_mismatch\")\n if package_manifest_path.exists():\n package_manifest_payload = json.loads(package_manifest_path.read_text(encoding=\"utf-8\"))\n if package_manifest_payload.get(\"candidate_id\") != release_id:\n failures.append(\"package_manifest_candidate_id_mismatch\")\n if package_manifest_payload.get(\"package\") != package_info.get(\"package\"):\n failures.append(\"package_path_snapshot_mismatch\")\n if package_manifest_payload.get(\"package_hash\") != package_info.get(\"package_hash\"):\n failures.append(\"package_hash_snapshot_mismatch\")\n else:\n package_verify = {\"passed\": False, \"failures\": [\"missing_package_manifest\"]}\n failures.append(\"missing_package_manifest\")\n commercial_verify = verify_commercial_release(release_dir)\n if not commercial_verify[\"passed\"]:\n failures.append(\"commercial_release_failed\")\n aws_package_verify = verify_aws_data_exchange_package(release_dir / \"aws_data_exchange\")\n if not aws_package_verify[\"passed\"]:\n failures.append(\"aws_data_exchange_package_failed\")\n sterilization_verify = verify_sterilized_bundle(release_dir / \"bundle\")\n if not sterilization_verify[\"passed\"]:\n failures.append(\"sterilization_failed\")\n event_count = len(read_product_events_from_release(release_dir / \"events.jsonl\"))\n if event_count != manifest.get(\"record_count\"):\n failures.append(\"record_count_mismatch\")\n if manifest.get(\"source_diversity\", 0) < 1:\n failures.append(\"source_diversity_empty\")\n return {\n \"passed\": not failures,\n \"manifest\": str(manifest_path),\n \"release_id\": manifest.get(\"release_id\"),\n \"family\": manifest.get(\"family\"),\n \"record_count\": event_count,\n \"lock_verify\": lock_verify,\n \"commercial_verify\": commercial_verify,\n \"aws_data_exchange_verify\": aws_package_verify,\n \"sterilization_verify\": sterilization_verify,\n \"package_verify\": package_verify,\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_autonomous_release(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_autonomous_release` is a function in `primitive_foundry.product_planner`. It belongs to the sterilization, release, marketplace, commercial, planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.verify_autonomous_release","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.verify_planner_queues::explain","input":"Module: primitive_foundry.product_planner\nDomains: planner\nSource path: primitive_foundry/product_planner.py\n\ndef verify_planner_queues(path: str | Path) -> dict[str, Any]:\n queues_root = Path(path)\n failures = []\n counts = {}\n seen_ids: set[str] = set()\n for family in PRODUCT_FAMILIES:\n queue_path = queues_root / f\"{family}.jsonl\"\n rows = read_queue_events(queue_path)\n counts[family] = len(rows)\n for index, row in enumerate(rows, start=1):\n if row.get(\"event\", {}).get(\"metadata\", {}).get(\"planner_family\") != family:\n failures.append(f\"{family}:{index}:wrong_family\")\n event_id = row.get(\"event\", {}).get(\"event_id\")\n if not event_id:\n failures.append(f\"{family}:{index}:missing_event_id\")\n elif event_id in seen_ids:\n failures.append(f\"{family}:{index}:duplicate_event_id:{event_id}\")\n seen_ids.add(event_id)\n source_path = row.get(\"event\", {}).get(\"source_path\")\n if source_path and not Path(source_path).expanduser().exists():\n failures.append(f\"{family}:{index}:missing_source\")\n return {\n \"passed\": not failures,\n \"queues_root\": str(queues_root),\n \"counts\": counts,\n \"queued_event_count\": sum(counts.values()),\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_planner_queues(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_planner_queues` is a function in `primitive_foundry.product_planner`. It belongs to the planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.verify_planner_queues","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.planner_health::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner\nSource path: primitive_foundry/product_planner.py\n\ndef planner_health(\n *,\n output_root: str | Path = artifact_path(\"products\", \"autonomous\"),\n state_path: str | Path | None = None,\n) -> dict[str, Any]:\n root = Path(output_root)\n state_file = Path(state_path) if state_path else root / \"PRODUCT_PLANNER_STATE.json\"\n state_verify = verify_planner_state(state_file)\n queue_verify = verify_planner_queues(root / \"queues\")\n release_results = []\n failures = []\n state = json.loads(state_file.read_text(encoding=\"utf-8\")) if state_file.exists() else {}\n for release in state.get(\"releases\", []):\n manifest = release.get(\"manifest\")\n if not manifest:\n failures.append(\"state_release_missing_manifest\")\n continue\n verified = verify_autonomous_release(manifest)\n release_results.append(verified)\n if not verified[\"passed\"]:\n failures.append(f\"release_failed:{manifest}\")\n return {\n \"passed\": state_verify[\"passed\"]\n and queue_verify[\"passed\"]\n and not failures\n and all(item[\"passed\"] for item in release_results),\n \"output_root\": str(root),\n \"state\": state_verify,\n \"queues\": queue_verify,\n \"release_count\": len(release_results),\n \"releases\": release_results,\n \"failures\": failures,\n }","instruction":"Explain the role of `def planner_health(*, output_root: str | Path=artifact_path('products', 'autonomous'), state_path: str | Path | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`planner_health` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.planner_health","task":"python_symbol_explanation"} {"id":"primitive_foundry.product_planner.read_product_events_from_release::explain","input":"Module: primitive_foundry.product_planner\nDomains: release, planner\nSource path: primitive_foundry/product_planner.py\n\ndef read_product_events_from_release(path: Path) -> list[dict[str, Any]]:\n if not path.exists():\n return []\n rows = []\n with path.open(\"r\", encoding=\"utf-8\") as handle:\n for line in handle:\n stripped = line.strip()\n if stripped:\n rows.append(json.loads(stripped))\n return rows","instruction":"Explain the role of `def read_product_events_from_release(path: Path) -> list[dict[str, Any]]` in Primitive Foundry.","output":"`read_product_events_from_release` is a function in `primitive_foundry.product_planner`. It belongs to the release, planner area of Primitive Foundry.","source_id":"primitive_foundry.product_planner.read_product_events_from_release","task":"python_symbol_explanation"} {"id":"primitive_foundry.promotion.promote_bundle::explain","input":"Module: primitive_foundry.promotion\nDomains: sterilization, dataset, router, benchmark\nSource path: primitive_foundry/promotion.py\n\ndef promote_bundle(\n *,\n dataset_path: str | Path,\n bundle_dir: str | Path,\n foundry_records: str | Path,\n output_manifest: str | Path,\n router: str = \"keyword\",\n registry_path: str | Path | None = None,\n min_pass_rate: float = 1.0,\n min_top_k: float = 1.0,\n require_audit: bool = True,\n work_dir: str | Path = \".\",\n) -> dict[str, Any]:\n benchmark = BenchmarkRunner(router_name=router, registry_path=registry_path).run_dataset(dataset_path)\n foundry_quality = verify_foundry_records(foundry_records)\n bundle_quality = verify_foundry_bundle(bundle_dir)\n sterilization_quality = bundle_quality.get(\"sterilization\", {\"passed\": False, \"failures\": [\"missing_sterilization_check\"]})\n audit = audit_local_paths(work_dir) if require_audit else {\"passed\": True, \"checks\": []}\n bundle_snapshot = snapshot_bundle(bundle_dir)\n foundry_snapshot = snapshot_foundry_records(foundry_records)\n\n gates = [\n {\n \"name\": \"benchmark_pass_rate\",\n \"passed\": benchmark[\"pass_rate\"] >= min_pass_rate,\n \"actual\": benchmark[\"pass_rate\"],\n \"threshold\": min_pass_rate,\n },\n {\n \"name\": \"benchmark_top_k_routing\",\n \"passed\": benchmark[\"metrics\"][\"top_k_routing\"] >= min_top_k,\n \"actual\": benchmark[\"metrics\"][\"top_k_routing\"],\n \"threshold\": min_top_k,\n },\n {\n \"name\": \"foundry_records_quality\",\n \"passed\": foundry_quality[\"passed\"],\n \"actual\": foundry_quality,\n \"threshold\": \"passed=true\",\n },\n {\n \"name\": \"bundle_quality\",\n \"passed\": bundle_quality[\"passed\"],\n \"actual\": bundle_quality,\n \"threshold\": \"passed=true\",\n },\n {\n \"name\": \"sterilization_quality\",\n \"passed\": sterilization_quality[\"passed\"],\n \"actual\": sterilization_quality,\n \"threshold\": \"passed=true\",\n },\n {\n \"name\": \"local_audit\",\n \"passed\": audit[\"passed\"],\n \"actual\": {\"passed\": audit[\"passed\"], \"checks\": audit[\"checks\"]},\n \"threshold\": \"passed=true\",\n },\n ]\n promoted = all(gate[\"passed\"] for gate in gates)\n manifest = {\n \"manifest_type\": \"aml_promotion_manifest\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"promoted\": promoted,\n \"dataset_path\": str(dataset_path),\n \"bundle_dir\": str(bundle_dir),\n \"foundry_records\": str(foundry_records),\n \"router\": router,\n \"registry_path\": str(registry_path) if registry_path else None,\n \"bundle_snapshot\": bundle_snapshot,\n \"foundry_records_snapshot\": foundry_snapshot,\n \"gates\": gates,\n }\n manifest[\"promotion_hash\"] = sha256_json({**manifest, \"promotion_hash\": \"\"})\n\n output = Path(output_manifest)\n output.parent.mkdir(parents=True, exist_ok=True)\n output.write_text(json.dumps(manifest, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return manifest","instruction":"Explain the role of `def promote_bundle(*, dataset_path: str | Path, bundle_dir: str | Path, foundry_records: str | Path, output_manifest: str | Path, router: str='keyword', registry_path: str | Path | None=None, min_pass_rate: float=1.0, min_top_k: float=1.0, require_audit: bool=True, work_dir: str | Path='.') -> dict[str, Any]` in Primitive Foundry.","output":"`promote_bundle` is a function in `primitive_foundry.promotion`. It belongs to the sterilization, dataset, router, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.promotion.promote_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.promotion.verify_promotion_manifest::explain","input":"Module: primitive_foundry.promotion\nDomains: foundry\nSource path: primitive_foundry/promotion.py\n\ndef verify_promotion_manifest(path: str | Path) -> dict[str, Any]:\n manifest_path = Path(path)\n with manifest_path.open(\"r\", encoding=\"utf-8\") as handle:\n manifest = json.load(handle)\n expected = sha256_json({**manifest, \"promotion_hash\": \"\"})\n failures = []\n if manifest.get(\"manifest_type\") != \"aml_promotion_manifest\":\n failures.append(\"invalid_manifest_type\")\n if manifest.get(\"promotion_hash\") != expected:\n failures.append(\"promotion_hash_mismatch\")\n if not manifest.get(\"promoted\"):\n failures.append(\"not_promoted\")\n failed_gates = [gate[\"name\"] for gate in manifest.get(\"gates\", []) if not gate.get(\"passed\")]\n if failed_gates:\n failures.append(\"failed_gates:\" + \",\".join(failed_gates))\n\n bundle_dir = manifest.get(\"bundle_dir\")\n if bundle_dir and \"bundle_snapshot\" in manifest:\n current_bundle = snapshot_bundle(bundle_dir)\n expected_bundle = manifest[\"bundle_snapshot\"]\n if current_bundle.get(\"bundle_hash\") != expected_bundle.get(\"bundle_hash\"):\n failures.append(\"bundle_snapshot_mismatch\")\n bundle_quality = verify_foundry_bundle(bundle_dir)\n if not bundle_quality[\"passed\"]:\n failures.append(\"bundle_verification_failed\")\n\n foundry_records = manifest.get(\"foundry_records\")\n if foundry_records and \"foundry_records_snapshot\" in manifest:\n current_foundry = snapshot_foundry_records(foundry_records)\n expected_foundry = manifest[\"foundry_records_snapshot\"]\n if current_foundry.get(\"records_hash\") != expected_foundry.get(\"records_hash\"):\n failures.append(\"foundry_records_snapshot_mismatch\")\n records_quality = verify_foundry_records(foundry_records)\n if not records_quality[\"passed\"]:\n failures.append(\"foundry_records_verification_failed\")\n return {\n \"passed\": not failures,\n \"manifest\": str(path),\n \"promoted\": bool(manifest.get(\"promoted\")),\n \"failures\": failures,\n \"gate_count\": len(manifest.get(\"gates\", [])),\n }","instruction":"Explain the role of `def verify_promotion_manifest(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_promotion_manifest` is a function in `primitive_foundry.promotion`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.promotion.verify_promotion_manifest","task":"python_symbol_explanation"} {"id":"primitive_foundry.pvtr_bridge.register_source_with_pvtr::explain","input":"Module: primitive_foundry.pvtr_bridge\nDomains: source_card\nSource path: primitive_foundry/pvtr_bridge.py\n\ndef register_source_with_pvtr(source_card: dict[str, Any], pvtr_endpoint: str) -> PvtrReceipt:\n payload = json.dumps(source_card, sort_keys=True, default=str)\n digest = hashlib.sha256(payload.encode(\"utf-8\")).hexdigest()\n return PvtrReceipt(\n record_id=str(source_card.get(\"record_id\") or source_card.get(\"source_id\") or digest[:12]),\n shelf_id=f\"shelf-{digest[:16]}\",\n orb_id=f\"orb-{digest[16:32]}\",\n chain_position=int(digest[:8], 16),\n payload_hash=digest,\n endpoint=pvtr_endpoint,\n )","instruction":"Explain the role of `def register_source_with_pvtr(source_card: dict[str, Any], pvtr_endpoint: str) -> PvtrReceipt` in Primitive Foundry.","output":"`register_source_with_pvtr` is a function in `primitive_foundry.pvtr_bridge`. It belongs to the source_card area of Primitive Foundry.","source_id":"primitive_foundry.pvtr_bridge.register_source_with_pvtr","task":"python_symbol_explanation"} {"id":"primitive_foundry.pvtr_bridge.write_pvtr_receipts_to_bundle::explain","input":"Module: primitive_foundry.pvtr_bridge\nDomains: atomic_write\nSource path: primitive_foundry/pvtr_bridge.py\n\ndef write_pvtr_receipts_to_bundle(bundle_dir: Path, receipts: list[PvtrReceipt]) -> None:\n bundle = Path(bundle_dir)\n payload = {\n \"schema\": \"primitive-pvtr-receipts.v1\",\n \"receipt_count\": len(receipts),\n \"receipts\": {receipt.record_id: asdict(receipt) for receipt in receipts},\n }\n atomic_write_json(bundle / \"PVTR_RECEIPTS.json\", payload)\n provenance_path = bundle / \"PROVENANCE_MANIFEST.json\"\n provenance = json.loads(provenance_path.read_text(encoding=\"utf-8\"))\n provenance[\"pvtr_receipts\"] = {\n \"receipt_count\": len(receipts),\n \"receipt_file\": \"PVTR_RECEIPTS.json\",\n \"receipt_hash\": sha256_bytes((bundle / \"PVTR_RECEIPTS.json\").read_bytes()),\n }\n atomic_write_json(provenance_path, provenance)\n rewrite_bundle_checksums(bundle)","instruction":"Explain the role of `def write_pvtr_receipts_to_bundle(bundle_dir: Path, receipts: list[PvtrReceipt]) -> None` in Primitive Foundry.","output":"`write_pvtr_receipts_to_bundle` is a function in `primitive_foundry.pvtr_bridge`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.pvtr_bridge.write_pvtr_receipts_to_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.pvtr_bridge.verify_record_against_pvtr::explain","input":"Module: primitive_foundry.pvtr_bridge\nDomains: foundry\nSource path: primitive_foundry/pvtr_bridge.py\n\ndef verify_record_against_pvtr(record_id: str, pvtr_endpoint: str, bundle_dir: Path | None = None) -> dict[str, Any]:\n if bundle_dir is None:\n return {\"passed\": False, \"record_id\": record_id, \"failures\": [\"bundle_dir_required_for_local_verification\"]}\n receipts_path = Path(bundle_dir) / \"PVTR_RECEIPTS.json\"\n if not receipts_path.exists():\n return {\"passed\": False, \"record_id\": record_id, \"failures\": [\"missing_pvtr_receipts\"]}\n receipts = json.loads(receipts_path.read_text(encoding=\"utf-8\")).get(\"receipts\", {})\n receipt = receipts.get(record_id)\n if not receipt:\n return {\"passed\": False, \"record_id\": record_id, \"failures\": [\"missing_record_receipt\"]}\n if receipt.get(\"endpoint\") != pvtr_endpoint:\n return {\"passed\": False, \"record_id\": record_id, \"failures\": [\"endpoint_mismatch\"]}\n return {\"passed\": True, \"record_id\": record_id, \"receipt\": receipt, \"failures\": []}","instruction":"Explain the role of `def verify_record_against_pvtr(record_id: str, pvtr_endpoint: str, bundle_dir: Path | None=None) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_record_against_pvtr` is a function in `primitive_foundry.pvtr_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.pvtr_bridge.verify_record_against_pvtr","task":"python_symbol_explanation"} {"id":"primitive_foundry.pvtr_bridge.bind_bundle_records_to_pvtr::explain","input":"Module: primitive_foundry.pvtr_bridge\nDomains: foundry\nSource path: primitive_foundry/pvtr_bridge.py\n\ndef bind_bundle_records_to_pvtr(bundle_dir: str | Path, pvtr_endpoint: str = \"local://pvtr\") -> dict[str, Any]:\n bundle = Path(bundle_dir)\n records = read_foundry_jsonl(bundle / \"source_foundry_records.jsonl\")\n receipts = [register_source_with_pvtr(record, pvtr_endpoint) for record in records]\n write_pvtr_receipts_to_bundle(bundle, receipts)\n return {\n \"bundle_dir\": str(bundle),\n \"endpoint\": pvtr_endpoint,\n \"receipt_count\": len(receipts),\n \"receipt_file\": str(bundle / \"PVTR_RECEIPTS.json\"),\n }","instruction":"Explain the role of `def bind_bundle_records_to_pvtr(bundle_dir: str | Path, pvtr_endpoint: str='local://pvtr') -> dict[str, Any]` in Primitive Foundry.","output":"`bind_bundle_records_to_pvtr` is a function in `primitive_foundry.pvtr_bridge`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.pvtr_bridge.bind_bundle_records_to_pvtr","task":"python_symbol_explanation"} {"id":"primitive_foundry.pvtr_bridge.rewrite_bundle_checksums::explain","input":"Module: primitive_foundry.pvtr_bridge\nDomains: atomic_write\nSource path: primitive_foundry/pvtr_bridge.py\n\ndef rewrite_bundle_checksums(bundle: Path) -> None:\n checksums = {}\n for path in sorted(item for item in bundle.rglob(\"*\") if item.is_file() and item.name != \"CHECKSUMS.sha256\"):\n checksums[str(path.relative_to(bundle))] = sha256_bytes(path.read_bytes())\n checksum_text = \"\".join(f\"{digest} {name}\\n\" for name, digest in sorted(checksums.items()))\n atomic_write_text(bundle / \"CHECKSUMS.sha256\", checksum_text)","instruction":"Explain the role of `def rewrite_bundle_checksums(bundle: Path) -> None` in Primitive Foundry.","output":"`rewrite_bundle_checksums` is a function in `primitive_foundry.pvtr_bridge`. It belongs to the atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.pvtr_bridge.rewrite_bundle_checksums","task":"python_symbol_explanation"} {"id":"primitive_foundry.release.review_promotion::explain","input":"Module: primitive_foundry.release\nDomains: release, atomic_write\nSource path: primitive_foundry/release.py\n\ndef review_promotion(\n *,\n manifest_path: str | Path,\n reviewer: str,\n decision: str,\n notes: str,\n output_path: str | Path,\n) -> dict[str, Any]:\n if decision not in ALLOWED_REVIEW_DECISIONS:\n raise ValueError(f\"Unsupported review decision: {decision}\")\n promotion_status = verify_promotion_manifest(manifest_path)\n if decision == \"approved\" and not promotion_status[\"passed\"]:\n raise ValueError(\"Cannot approve a promotion manifest that does not verify.\")\n with Path(manifest_path).open(\"r\", encoding=\"utf-8\") as handle:\n promotion_manifest = json.load(handle)\n review = {\n \"manifest_type\": \"aml_review_manifest\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"promotion_manifest\": str(manifest_path),\n \"promotion_hash\": promotion_manifest.get(\"promotion_hash\"),\n \"promotion_passed\": promotion_status[\"passed\"],\n \"reviewer\": reviewer,\n \"decision\": decision,\n \"notes\": notes,\n }\n review[\"review_hash\"] = sha256_json({**review, \"review_hash\": \"\"})\n output = Path(output_path)\n locked_atomic_write_json(output, review, keep_lock=False)\n return review","instruction":"Explain the role of `def review_promotion(*, manifest_path: str | Path, reviewer: str, decision: str, notes: str, output_path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`review_promotion` is a function in `primitive_foundry.release`. It belongs to the release, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.release.review_promotion","task":"python_symbol_explanation"} {"id":"primitive_foundry.release.verify_review_manifest::explain","input":"Module: primitive_foundry.release\nDomains: release\nSource path: primitive_foundry/release.py\n\ndef verify_review_manifest(path: str | Path) -> dict[str, Any]:\n with Path(path).open(\"r\", encoding=\"utf-8\") as handle:\n review = json.load(handle)\n failures = []\n if review.get(\"manifest_type\") != \"aml_review_manifest\":\n failures.append(\"invalid_manifest_type\")\n expected_hash = sha256_json({**review, \"review_hash\": \"\"})\n if review.get(\"review_hash\") != expected_hash:\n failures.append(\"review_hash_mismatch\")\n if review.get(\"decision\") not in ALLOWED_REVIEW_DECISIONS:\n failures.append(\"invalid_decision\")\n promotion_manifest = review.get(\"promotion_manifest\")\n if not promotion_manifest:\n failures.append(\"missing_promotion_manifest\")\n else:\n promotion_status = verify_promotion_manifest(promotion_manifest)\n if promotion_status[\"passed\"] != review.get(\"promotion_passed\"):\n failures.append(\"promotion_status_changed\")\n with Path(promotion_manifest).open(\"r\", encoding=\"utf-8\") as handle:\n current_promotion = json.load(handle)\n if current_promotion.get(\"promotion_hash\") != review.get(\"promotion_hash\"):\n failures.append(\"promotion_hash_changed\")\n if review.get(\"decision\") == \"approved\" and not promotion_status[\"passed\"]:\n failures.append(\"approved_failed_promotion\")\n return {\n \"passed\": not failures,\n \"manifest\": str(path),\n \"decision\": review.get(\"decision\"),\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_review_manifest(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_review_manifest` is a function in `primitive_foundry.release`. It belongs to the release area of Primitive Foundry.","source_id":"primitive_foundry.release.verify_review_manifest","task":"python_symbol_explanation"} {"id":"primitive_foundry.release.build_release_index::explain","input":"Module: primitive_foundry.release\nDomains: release, dataset, atomic_write\nSource path: primitive_foundry/release.py\n\ndef build_release_index(\n *,\n promotions_dir: str | Path,\n reviews_dir: str | Path,\n output_path: str | Path,\n) -> dict[str, Any]:\n promotions = []\n for manifest_path in sorted(Path(promotions_dir).glob(\"*.promotion.json\")):\n status = verify_promotion_manifest(manifest_path)\n with manifest_path.open(\"r\", encoding=\"utf-8\") as handle:\n manifest = json.load(handle)\n promotions.append(\n {\n \"promotion_manifest\": str(manifest_path),\n \"promotion_hash\": manifest.get(\"promotion_hash\"),\n \"promoted\": manifest.get(\"promoted\"),\n \"verified\": status[\"passed\"],\n \"dataset_path\": manifest.get(\"dataset_path\"),\n \"bundle_dir\": manifest.get(\"bundle_dir\"),\n \"foundry_records\": manifest.get(\"foundry_records\"),\n }\n )\n\n reviews = []\n for review_path in sorted(Path(reviews_dir).glob(\"*.review.json\")):\n status = verify_review_manifest(review_path)\n with review_path.open(\"r\", encoding=\"utf-8\") as handle:\n review = json.load(handle)\n reviews.append(\n {\n \"review_manifest\": str(review_path),\n \"review_hash\": review.get(\"review_hash\"),\n \"promotion_manifest\": review.get(\"promotion_manifest\"),\n \"promotion_hash\": review.get(\"promotion_hash\"),\n \"decision\": review.get(\"decision\"),\n \"verified\": status[\"passed\"],\n }\n )\n\n index = {\n \"manifest_type\": \"aml_release_index\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"promotions\": promotions,\n \"reviews\": reviews,\n }\n index[\"release_index_hash\"] = sha256_json({**index, \"release_index_hash\": \"\"})\n output = Path(output_path)\n locked_atomic_write_json(output, index, keep_lock=False)\n return index","instruction":"Explain the role of `def build_release_index(*, promotions_dir: str | Path, reviews_dir: str | Path, output_path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`build_release_index` is a function in `primitive_foundry.release`. It belongs to the release, dataset, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.release.build_release_index","task":"python_symbol_explanation"} {"id":"primitive_foundry.release.verify_release_index::explain","input":"Module: primitive_foundry.release\nDomains: release\nSource path: primitive_foundry/release.py\n\ndef verify_release_index(path: str | Path) -> dict[str, Any]:\n with Path(path).open(\"r\", encoding=\"utf-8\") as handle:\n index = json.load(handle)\n failures = []\n if index.get(\"manifest_type\") != \"aml_release_index\":\n failures.append(\"invalid_manifest_type\")\n expected_hash = sha256_json({**index, \"release_index_hash\": \"\"})\n if index.get(\"release_index_hash\") != expected_hash:\n failures.append(\"release_index_hash_mismatch\")\n for promotion in index.get(\"promotions\", []):\n status = verify_promotion_manifest(promotion[\"promotion_manifest\"])\n if status[\"passed\"] != promotion.get(\"verified\"):\n failures.append(f\"promotion_status_changed:{promotion['promotion_manifest']}\")\n for review in index.get(\"reviews\", []):\n status = verify_review_manifest(review[\"review_manifest\"])\n if status[\"passed\"] != review.get(\"verified\"):\n failures.append(f\"review_status_changed:{review['review_manifest']}\")\n return {\n \"passed\": not failures,\n \"index\": str(path),\n \"promotion_count\": len(index.get(\"promotions\", [])),\n \"review_count\": len(index.get(\"reviews\", [])),\n \"failures\": failures,\n }","instruction":"Explain the role of `def verify_release_index(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_release_index` is a function in `primitive_foundry.release`. It belongs to the release area of Primitive Foundry.","source_id":"primitive_foundry.release.verify_release_index","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.tokenize::explain","input":"Module: primitive_foundry.router\nDomains: router\nSource path: primitive_foundry/router.py\n\ndef tokenize(text: str) -> set[str]:\n return set(TOKEN_RE.findall(text.lower()))","instruction":"Explain the role of `def tokenize(text: str) -> set[str]` in Primitive Foundry.","output":"`tokenize` is a function in `primitive_foundry.router`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.router.tokenize","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.KeywordRouter::explain","input":"Module: primitive_foundry.router\nDomains: router, benchmark\nSource path: primitive_foundry/router.py\n\nclass KeywordRouter:\n \"\"\"Deterministic baseline router for private benchmark bootstrapping.\"\"\"\n\n def __init__(self, registry: CellRegistry, top_k: int = 5) -> None:\n self.registry = registry\n self.top_k = top_k\n\n def route(self, record: FoundryRecord) -> RouterDecision:\n query_tokens = tokenize(record.query)\n replacements = self.registry.replacements()\n candidates: list[tuple[str, float]] = []\n\n for cell in self.registry.active_cells():\n keyword_hits = len(query_tokens.intersection(cell.keywords))\n domain_hits = len(query_tokens.intersection(tokenize(cell.domain_path.replace(\".\", \" \"))))\n score = keyword_hits + (0.5 * domain_hits) + (0.1 * cell.trust_score)\n if record.stale_cell_id and replacements.get(record.stale_cell_id) == cell.cell_id:\n score += 1.0\n candidates.append((cell.cell_id, score))\n\n candidates.sort(key=lambda item: item[1], reverse=True)\n selected_cell_id, score = candidates[0]\n return RouterDecision(\n selected_cell_id=selected_cell_id,\n score=score,\n candidates=candidates[: self.top_k],\n top_k=self.top_k,\n )","instruction":"Explain the role of `class KeywordRouter` in Primitive Foundry.","output":"`KeywordRouter` is a class in `primitive_foundry.router`. It belongs to the router, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.router.KeywordRouter","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.HashedEmbeddingRouter::explain","input":"Module: primitive_foundry.router\nDomains: router\nSource path: primitive_foundry/router.py\n\nclass HashedEmbeddingRouter:\n \"\"\"Small local embedding-style router using hashed bag-of-token vectors.\"\"\"\n\n def __init__(self, registry: CellRegistry, top_k: int = 5, dimensions: int = 128) -> None:\n self.registry = registry\n self.top_k = top_k\n self.dimensions = dimensions\n self._cell_vectors = {\n cell.cell_id: self._cell_vector(cell)\n for cell in self.registry.active_cells()\n }\n\n def route(self, record: FoundryRecord) -> RouterDecision:\n query_vector = self._text_vector(record.query)\n replacements = self.registry.replacements()\n candidates: list[tuple[str, float]] = []\n\n for cell in self.registry.active_cells():\n score = cosine(query_vector, self._cell_vectors[cell.cell_id])\n if record.stale_cell_id and replacements.get(record.stale_cell_id) == cell.cell_id:\n score += 0.25\n candidates.append((cell.cell_id, score))\n\n candidates.sort(key=lambda item: item[1], reverse=True)\n selected_cell_id, score = candidates[0]\n return RouterDecision(\n selected_cell_id=selected_cell_id,\n score=score,\n candidates=candidates[: self.top_k],\n top_k=self.top_k,\n )\n\n def _cell_vector(self, cell: Cell) -> list[float]:\n text = \" \".join(\n [\n cell.cell_id,\n cell.domain_path.replace(\".\", \" \"),\n \" \".join(cell.keywords),\n cell.answer_template,\n ]\n )\n return self._text_vector(text)\n\n def _text_vector(self, text: str) -> list[float]:\n return text_vector(text, self.dimensions)","instruction":"Explain the role of `class HashedEmbeddingRouter` in Primitive Foundry.","output":"`HashedEmbeddingRouter` is a class in `primitive_foundry.router`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.router.HashedEmbeddingRouter","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.char_ngrams::explain","input":"Module: primitive_foundry.router\nDomains: router\nSource path: primitive_foundry/router.py\n\ndef char_ngrams(token: str, width: int = 3) -> list[str]:\n if len(token) <= width:\n return [token]\n return [token[index : index + width] for index in range(len(token) - width + 1)]","instruction":"Explain the role of `def char_ngrams(token: str, width: int=3) -> list[str]` in Primitive Foundry.","output":"`char_ngrams` is a function in `primitive_foundry.router`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.router.char_ngrams","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.stable_hash::explain","input":"Module: primitive_foundry.router\nDomains: router\nSource path: primitive_foundry/router.py\n\ndef stable_hash(text: str) -> int:\n value = 2166136261\n for char in text:\n value ^= ord(char)\n value *= 16777619\n value &= 0xFFFFFFFF\n return value","instruction":"Explain the role of `def stable_hash(text: str) -> int` in Primitive Foundry.","output":"`stable_hash` is a function in `primitive_foundry.router`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.router.stable_hash","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.normalize::explain","input":"Module: primitive_foundry.router\nDomains: router\nSource path: primitive_foundry/router.py\n\ndef normalize(vector: list[float]) -> list[float]:\n norm = sqrt(sum(value * value for value in vector))\n if norm == 0:\n return vector\n return [value / norm for value in vector]","instruction":"Explain the role of `def normalize(vector: list[float]) -> list[float]` in Primitive Foundry.","output":"`normalize` is a function in `primitive_foundry.router`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.router.normalize","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.cosine::explain","input":"Module: primitive_foundry.router\nDomains: router\nSource path: primitive_foundry/router.py\n\ndef cosine(left: list[float], right: list[float]) -> float:\n return sum(left_value * right_value for left_value, right_value in zip(left, right))","instruction":"Explain the role of `def cosine(left: list[float], right: list[float]) -> float` in Primitive Foundry.","output":"`cosine` is a function in `primitive_foundry.router`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.router.cosine","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.text_vector::explain","input":"Module: primitive_foundry.router\nDomains: router\nSource path: primitive_foundry/router.py\n\ndef text_vector(text: str, dimensions: int) -> list[float]:\n vector = [0.0] * dimensions\n tokens = tokenize(text)\n for token in tokens:\n vector[stable_hash(token) % dimensions] += 1.0\n for ngram in char_ngrams(token):\n vector[stable_hash(ngram) % dimensions] += 0.25\n return normalize(vector)","instruction":"Explain the role of `def text_vector(text: str, dimensions: int) -> list[float]` in Primitive Foundry.","output":"`text_vector` is a function in `primitive_foundry.router`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.router.text_vector","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.load_router_model::explain","input":"Module: primitive_foundry.router\nDomains: router\nSource path: primitive_foundry/router.py\n\ndef load_router_model(model_path: str | Path) -> dict[str, Any]:\n with Path(model_path).open(\"r\", encoding=\"utf-8\") as handle:\n payload = json.load(handle)\n if payload.get(\"model_type\") != \"centroid-router\":\n raise ValueError(f\"Unsupported router model type in {model_path}\")\n return payload","instruction":"Explain the role of `def load_router_model(model_path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`load_router_model` is a function in `primitive_foundry.router`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.router.load_router_model","task":"python_symbol_explanation"} {"id":"primitive_foundry.router.build_router::explain","input":"Module: primitive_foundry.router\nDomains: router\nSource path: primitive_foundry/router.py\n\ndef build_router(\n name: str,\n registry: CellRegistry,\n top_k: int = 5,\n model_path: str | Path | None = None,\n) -> KeywordRouter | HashedEmbeddingRouter | TrainedCentroidRouter:\n if name == \"keyword\":\n return KeywordRouter(registry=registry, top_k=top_k)\n if name == \"hashed-embedding\":\n return HashedEmbeddingRouter(registry=registry, top_k=top_k)\n if name == \"trained\":\n if model_path is None:\n raise ValueError(\"router 'trained' requires model_path\")\n return TrainedCentroidRouter(registry=registry, model_path=model_path, top_k=top_k)\n raise ValueError(f\"Unknown router: {name}\")","instruction":"Explain the role of `def build_router(name: str, registry: CellRegistry, top_k: int=5, model_path: str | Path | None=None) -> KeywordRouter | HashedEmbeddingRouter | TrainedCentroidRouter` in Primitive Foundry.","output":"`build_router` is a function in `primitive_foundry.router`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.router.build_router","task":"python_symbol_explanation"} {"id":"primitive_foundry.runner.BenchmarkRunner::explain","input":"Module: primitive_foundry.runner\nDomains: dataset, router, benchmark\nSource path: primitive_foundry/runner.py\n\nclass BenchmarkRunner:\n def __init__(\n self,\n registry: CellRegistry | None = None,\n registry_path: str | Path | None = None,\n top_k: int = 5,\n router_name: str = \"keyword\",\n router_path: str | Path | None = None,\n seed: int = 0,\n ) -> None:\n if registry is not None and registry_path is not None:\n raise ValueError(\"Pass either registry or registry_path, not both\")\n self.registry = registry or (CellRegistry.from_json(registry_path) if registry_path else CellRegistry())\n self.registry_path = str(registry_path) if registry_path else None\n self.router_name = router_name\n self.router_path = str(router_path) if router_path else None\n self.seed = seed\n random.seed(seed)\n self.router = build_router(router_name, self.registry, top_k=top_k, model_path=router_path)\n\n def run_dataset(self, dataset_path: str | Path) -> dict[str, object]:\n records = load_jsonl(dataset_path)\n results: list[EvalResult] = []\n\n for record in records:\n decision = self.router.route(record)\n response = self.registry.answer(decision.selected_cell_id, record.query)\n scores = {\n \"routing\": score_routing(record, decision),\n \"top_k_routing\": score_top_k_routing(record, decision),\n \"expected_cells_coverage\": score_expected_cells_coverage(record, decision),\n \"replacement\": score_replacement(record, decision, self.registry),\n \"staleness_detection\": score_staleness_detection(record, self.registry),\n \"provenance\": score_provenance(response),\n \"answer_overlap\": score_answer_contains_expected(record, response),\n }\n passed = scores[\"routing\"] == 1.0 and scores[\"provenance\"] == 1.0\n if len(record.expected_cell_ids) > 1:\n passed = scores[\"expected_cells_coverage\"] == 1.0 and scores[\"provenance\"] == 1.0\n if record.task in {\"replace_cell_without_global_retrain\", \"apoptosis_event_replay\", \"resolve_old_new_conflict\"}:\n passed = passed and scores[\"replacement\"] == 1.0\n if record.task == \"detect_stale_cell\":\n passed = passed and scores[\"staleness_detection\"] == 1.0\n\n results.append(\n EvalResult(\n record_id=record.record_id,\n task=record.task,\n selected_cell_id=decision.selected_cell_id,\n expected_cell_id=record.expected_cell_id,\n expected_cell_ids=record.expected_cell_ids,\n candidates=decision.candidates,\n scores=scores,\n passed=passed,\n answer=response.answer,\n )\n )\n\n return self._summarize(results)\n\n def _summarize(self, results: list[EvalResult]) -> dict[str, object]:\n totals: dict[str, list[float]] = {}\n for result in results:\n for name, score in result.scores.items():\n totals.setdefault(name, []).append(score)\n\n metrics = {\n name: sum(values) / len(values)\n for name, values in sorted(totals.items())\n }\n pass_rate = sum(1 for result in results if result.passed) / len(results)\n\n return {\n \"benchmark\": \"Primitive Foundry Benchmark\",\n \"created_at\": deterministic_timestamp(self.seed),\n \"seed\": self.seed,\n \"router\": self.router_name,\n \"router_path\": self.router_path,\n \"registry_path\": self.registry_path,\n \"record_count\": len(results),\n \"pass_rate\": pass_rate,\n \"metrics\": metrics,\n \"results\": [asdict(result) for result in results],\n }","instruction":"Explain the role of `class BenchmarkRunner` in Primitive Foundry.","output":"`BenchmarkRunner` is a class in `primitive_foundry.runner`. It belongs to the dataset, router, benchmark area of Primitive Foundry.","source_id":"primitive_foundry.runner.BenchmarkRunner","task":"python_symbol_explanation"} {"id":"primitive_foundry.runner.write_report::explain","input":"Module: primitive_foundry.runner\nDomains: foundry\nSource path: primitive_foundry/runner.py\n\ndef write_report(report: dict[str, object], output_dir: str | Path = \"runs\") -> Path:\n target_dir = Path(output_dir)\n target_dir.mkdir(parents=True, exist_ok=True)\n stamp = datetime.now(timezone.utc).strftime(\"%Y%m%dT%H%M%S%fZ\")\n report_path = target_dir / f\"aml_report_{stamp}.json\"\n with report_path.open(\"w\", encoding=\"utf-8\") as handle:\n json.dump(report, handle, indent=2)\n handle.write(\"\\n\")\n write_csv_report(report, target_dir / f\"aml_report_{stamp}.csv\")\n write_html_report(report, target_dir / f\"aml_report_{stamp}.html\")\n return report_path","instruction":"Explain the role of `def write_report(report: dict[str, object], output_dir: str | Path='runs') -> Path` in Primitive Foundry.","output":"`write_report` is a function in `primitive_foundry.runner`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.runner.write_report","task":"python_symbol_explanation"} {"id":"primitive_foundry.runner.deterministic_timestamp::explain","input":"Module: primitive_foundry.runner\nDomains: foundry\nSource path: primitive_foundry/runner.py\n\ndef deterministic_timestamp(seed: int) -> str:\n if seed == 0:\n return \"1970-01-01T00:00:00+00:00\"\n return datetime.fromtimestamp(seed, tz=timezone.utc).isoformat()","instruction":"Explain the role of `def deterministic_timestamp(seed: int) -> str` in Primitive Foundry.","output":"`deterministic_timestamp` is a function in `primitive_foundry.runner`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.runner.deterministic_timestamp","task":"python_symbol_explanation"} {"id":"primitive_foundry.runner.write_csv_report::explain","input":"Module: primitive_foundry.runner\nDomains: foundry\nSource path: primitive_foundry/runner.py\n\ndef write_csv_report(report: dict[str, object], report_path: Path) -> None:\n results = report[\"results\"]\n assert isinstance(results, list)\n with report_path.open(\"w\", encoding=\"utf-8\", newline=\"\") as handle:\n writer = csv.DictWriter(\n handle,\n fieldnames=[\n \"record_id\",\n \"task\",\n \"passed\",\n \"selected_cell_id\",\n \"expected_cell_id\",\n \"routing\",\n \"top_k_routing\",\n \"replacement\",\n \"staleness_detection\",\n \"provenance\",\n \"expected_cells_coverage\",\n ],\n )\n writer.writeheader()\n for result in results:\n scores = result[\"scores\"]\n writer.writerow(\n {\n \"record_id\": result[\"record_id\"],\n \"task\": result[\"task\"],\n \"passed\": result[\"passed\"],\n \"selected_cell_id\": result[\"selected_cell_id\"],\n \"expected_cell_id\": result[\"expected_cell_id\"],\n \"routing\": scores[\"routing\"],\n \"top_k_routing\": scores[\"top_k_routing\"],\n \"replacement\": scores[\"replacement\"],\n \"staleness_detection\": scores[\"staleness_detection\"],\n \"provenance\": scores[\"provenance\"],\n \"expected_cells_coverage\": scores[\"expected_cells_coverage\"],\n }\n )","instruction":"Explain the role of `def write_csv_report(report: dict[str, object], report_path: Path) -> None` in Primitive Foundry.","output":"`write_csv_report` is a function in `primitive_foundry.runner`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.runner.write_csv_report","task":"python_symbol_explanation"} {"id":"primitive_foundry.sale_binding.bind_sale::explain","input":"Module: primitive_foundry.sale_binding\nDomains: license, signature\nSource path: primitive_foundry/sale_binding.py\n\ndef bind_sale(\n *,\n bundle_signature: Path,\n private_key_path: Path,\n buyer_name: str,\n buyer_email_hash: str,\n transaction_id: str,\n channel: str,\n license_tier: str,\n output_dir: Path,\n publisher_key_id: str = \"po-2026-05-A\",\n build_context: BuildContext = DEFAULT_BUILD_CONTEXT,\n) -> Path:\n output_dir.mkdir(parents=True, exist_ok=True)\n payload = {\n \"publisher\": \"Primitive Origins LLC\",\n \"publisher_key_id\": publisher_key_id,\n \"buyer_name\": buyer_name,\n \"buyer_email_hash\": buyer_email_hash,\n \"transaction_id\": transaction_id,\n \"channel\": channel,\n \"license_tier\": license_tier,\n \"bundle_signature_hash\": sha256_bytes(Path(bundle_signature).read_bytes()),\n \"sold_at\": build_context.now(),\n \"expires_at\": None,\n }\n private = load_private_key(Path(private_key_path).read_bytes())\n payload[\"binding_signature\"] = base64.b64encode(private.sign(canonical(payload))).decode(\"ascii\")\n path = output_dir / \"SALE_BINDING.json\"\n path.write_text(json.dumps(payload, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return path","instruction":"Explain the role of `def bind_sale(*, bundle_signature: Path, private_key_path: Path, buyer_name: str, buyer_email_hash: str, transaction_id: str, channel: str, license_tier: str, output_dir: Path, publisher_key_id: str='po-2026-05-A', build_context: BuildContext=DEFAULT_BUILD_CONTEXT) -> Path` in Primitive Foundry.","output":"`bind_sale` is a function in `primitive_foundry.sale_binding`. It belongs to the license, signature area of Primitive Foundry.","source_id":"primitive_foundry.sale_binding.bind_sale","task":"python_symbol_explanation"} {"id":"primitive_foundry.sale_binding.verify_sale_binding::explain","input":"Module: primitive_foundry.sale_binding\nDomains: signature\nSource path: primitive_foundry/sale_binding.py\n\ndef verify_sale_binding(path: Path, public_key_pem: bytes) -> dict[str, Any]:\n payload = json.loads(Path(path).read_text(encoding=\"utf-8\"))\n signature = base64.b64decode(payload[\"binding_signature\"])\n public = load_public_key(public_key_pem)\n public.verify(signature, canonical(payload))\n return {\"passed\": True, \"binding\": payload}","instruction":"Explain the role of `def verify_sale_binding(path: Path, public_key_pem: bytes) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_sale_binding` is a function in `primitive_foundry.sale_binding`. It belongs to the signature area of Primitive Foundry.","source_id":"primitive_foundry.sale_binding.verify_sale_binding","task":"python_symbol_explanation"} {"id":"primitive_foundry.sale_binding.canonical::explain","input":"Module: primitive_foundry.sale_binding\nDomains: signature\nSource path: primitive_foundry/sale_binding.py\n\ndef canonical(payload: dict[str, Any]) -> bytes:\n unsigned = {key: value for key, value in payload.items() if key != \"binding_signature\"}\n return json.dumps(unsigned, sort_keys=True, separators=(\",\", \":\"), default=str).encode(\"utf-8\")","instruction":"Explain the role of `def canonical(payload: dict[str, Any]) -> bytes` in Primitive Foundry.","output":"`canonical` is a function in `primitive_foundry.sale_binding`. It belongs to the signature area of Primitive Foundry.","source_id":"primitive_foundry.sale_binding.canonical","task":"python_symbol_explanation"} {"id":"primitive_foundry.sale_binding.load_private_key::explain","input":"Module: primitive_foundry.sale_binding\nDomains: foundry\nSource path: primitive_foundry/sale_binding.py\n\ndef load_private_key(private_key: bytes) -> Ed25519PrivateKey:\n loaded = serialization.load_pem_private_key(private_key, password=None)\n if not isinstance(loaded, Ed25519PrivateKey):\n raise TypeError(\"private_key_must_be_ed25519\")\n return loaded","instruction":"Explain the role of `def load_private_key(private_key: bytes) -> Ed25519PrivateKey` in Primitive Foundry.","output":"`load_private_key` is a function in `primitive_foundry.sale_binding`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.sale_binding.load_private_key","task":"python_symbol_explanation"} {"id":"primitive_foundry.sale_binding.load_public_key::explain","input":"Module: primitive_foundry.sale_binding\nDomains: foundry\nSource path: primitive_foundry/sale_binding.py\n\ndef load_public_key(public_key: bytes) -> Ed25519PublicKey:\n loaded = serialization.load_pem_public_key(public_key)\n if not isinstance(loaded, Ed25519PublicKey):\n raise TypeError(\"public_key_must_be_ed25519\")\n return loaded","instruction":"Explain the role of `def load_public_key(public_key: bytes) -> Ed25519PublicKey` in Primitive Foundry.","output":"`load_public_key` is a function in `primitive_foundry.sale_binding`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.sale_binding.load_public_key","task":"python_symbol_explanation"} {"id":"primitive_foundry.sample.build_buyer_preview::explain","input":"Module: primitive_foundry.sample\nDomains: release, dataset, atomic_write\nSource path: primitive_foundry/sample.py\n\ndef build_buyer_preview(\n release_dir: Path,\n preview_records: int = 10,\n redact_ground_truth: bool = True,\n) -> Path:\n release = Path(release_dir)\n bundle = release / \"bundle\"\n source_records = read_foundry_jsonl(bundle / \"source_foundry_records.jsonl\")\n preview_dir = bundle / \"preview\"\n preview_dir.mkdir(parents=True, exist_ok=True)\n rows = [preview_record(record, redact_ground_truth=redact_ground_truth) for record in source_records[:preview_records]]\n atomic_write_jsonl(preview_dir / \"preview_records.jsonl\", rows)\n for relative in (\"README.md\", \"DATASET_CARD.md\", \"SCHEMA.json\", \"QUALITY_REPORT.md\"):\n source = bundle / relative\n if source.exists():\n target = preview_dir / relative\n if source.suffix == \".json\":\n atomic_write_json(target, json.loads(source.read_text(encoding=\"utf-8\")))\n else:\n atomic_write_text(target, source.read_text(encoding=\"utf-8\"))\n manifest = {\n \"manifest_type\": \"aml_buyer_preview\",\n \"record_count\": len(rows),\n \"redact_ground_truth\": redact_ground_truth,\n \"raw_sources_included\": False,\n \"preview_records\": \"preview_records.jsonl\",\n \"preview_hash\": sha256_bytes((preview_dir / \"preview_records.jsonl\").read_bytes()),\n }\n atomic_write_json(preview_dir / \"PREVIEW_MANIFEST.json\", manifest)\n refresh_bundle_checksums(bundle)\n return preview_dir","instruction":"Explain the role of `def build_buyer_preview(release_dir: Path, preview_records: int=10, redact_ground_truth: bool=True) -> Path` in Primitive Foundry.","output":"`build_buyer_preview` is a function in `primitive_foundry.sample`. It belongs to the release, dataset, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.sample.build_buyer_preview","task":"python_symbol_explanation"} {"id":"primitive_foundry.sample.preview_record::explain","input":"Module: primitive_foundry.sample\nDomains: release, dataset\nSource path: primitive_foundry/sample.py\n\ndef preview_record(record: dict[str, Any], *, redact_ground_truth: bool) -> dict[str, Any]:\n features = dict(record.get(\"features\") or {})\n labels = dict(record.get(\"labels\") or {})\n if redact_ground_truth:\n for key in (\"expected_cell_id\", \"expected_cell_ids\", \"stale_cell_id\", \"replacement_for\"):\n features.pop(key, None)\n labels.pop(\"release_candidate\", None)\n return {\n \"record_id\": record.get(\"record_id\"),\n \"dataset_family\": record.get(\"dataset_family\"),\n \"dataset_version\": record.get(\"dataset_version\"),\n \"rubric_id\": record.get(\"rubric_id\"),\n \"buyer_task\": features.get(\"buyer_task\"),\n \"rubric\": features.get(\"rubric\"),\n \"product_family\": labels.get(\"product_family\") or features.get(\"product_family\"),\n \"features\": features,\n \"labels\": labels,\n }","instruction":"Explain the role of `def preview_record(record: dict[str, Any], *, redact_ground_truth: bool) -> dict[str, Any]` in Primitive Foundry.","output":"`preview_record` is a function in `primitive_foundry.sample`. It belongs to the release, dataset area of Primitive Foundry.","source_id":"primitive_foundry.sample.preview_record","task":"python_symbol_explanation"} {"id":"primitive_foundry.schema.FoundryRecord::explain","input":"Module: primitive_foundry.schema\nDomains: license\nSource path: primitive_foundry/schema.py\n\nclass FoundryRecord:\n record_id: str\n query: str\n expected_answer: str\n domain_path: str\n expected_cell_id: str\n valid_from: str\n expected_cell_ids: list[str] = field(default_factory=list)\n valid_until: str | None = None\n supersedes: str | None = None\n replacement_for: str | None = None\n stale_cell_id: str | None = None\n source_type: str = \"synthetic\"\n license: str = \"private-synthetic\"\n task: str = \"route_query_to_cell\"\n tags: list[str] = field(default_factory=list)\n metadata: dict[str, Any] = field(default_factory=dict)\n rubric_id: str = \"\"\n domain_review: dict[str, Any] = field(default_factory=dict)\n family_fields: dict[str, Any] = field(default_factory=dict)\n\n @classmethod\n def from_dict(cls, data: dict[str, Any]) -> \"FoundryRecord\":\n from .migrations import upgrade_record\n\n data = upgrade_record(data)\n required = [\n \"record_id\",\n \"query\",\n \"expected_answer\",\n \"domain_path\",\n \"expected_cell_id\",\n \"valid_from\",\n ]\n missing = [key for key in required if key not in data]\n if missing:\n raise ValueError(f\"Foundry record missing required fields: {', '.join(missing)}\")\n\n metadata = dict(data.get(\"metadata\", {}))\n rubric = data.get(\"rubric\") or metadata.get(\"rubric\") or {}\n buyer_task = data.get(\"buyer_task\") or metadata.get(\"buyer_task\") or {}\n rubric_id = (\n data.get(\"rubric_id\")\n or metadata.get(\"rubric_id\")\n or (rubric.get(\"rubric_id\") if isinstance(rubric, dict) else \"\")\n or (rubric.get(\"id\") if isinstance(rubric, dict) else \"\")\n or (buyer_task.get(\"rubric_id\") if isinstance(buyer_task, dict) else \"\")\n or \"\"\n )\n\n return cls(\n record_id=str(data[\"record_id\"]),\n query=str(data[\"query\"]),\n expected_answer=str(data[\"expected_answer\"]),\n domain_path=str(data[\"domain_path\"]),\n expected_cell_id=str(data[\"expected_cell_id\"]),\n expected_cell_ids=list(data.get(\"expected_cell_ids\", [str(data[\"expected_cell_id\"])])),\n valid_from=str(data[\"valid_from\"]),\n valid_until=data.get(\"valid_until\"),\n supersedes=data.get(\"supersedes\"),\n replacement_for=data.get(\"replacement_for\"),\n stale_cell_id=data.get(\"stale_cell_id\"),\n source_type=str(data.get(\"source_type\", \"synthetic\")),\n license=str(data.get(\"license\", \"private-synthetic\")),\n task=str(data.get(\"task\", \"route_query_to_cell\")),\n tags=list(data.get(\"tags\", [])),\n metadata=metadata,\n rubric_id=str(rubric_id),\n domain_review=dict(data.get(\"domain_review\") or metadata.get(\"domain_review\") or {}),\n family_fields=dict(data.get(\"family_fields\") or metadata.get(\"family_metadata\") or {}),\n )","instruction":"Explain the role of `class FoundryRecord` in Primitive Foundry.","output":"`FoundryRecord` is a class in `primitive_foundry.schema`. It belongs to the license area of Primitive Foundry.","source_id":"primitive_foundry.schema.FoundryRecord","task":"python_symbol_explanation"} {"id":"primitive_foundry.schema.Cell::explain","input":"Module: primitive_foundry.schema\nDomains: foundry\nSource path: primitive_foundry/schema.py\n\nclass Cell:\n cell_id: str\n domain_path: str\n valid_from: str\n valid_until: str | None\n trust_score: float\n status: str\n keywords: tuple[str, ...]\n answer_template: str\n supersedes: str | None = None","instruction":"Explain the role of `class Cell` in Primitive Foundry.","output":"`Cell` is a class in `primitive_foundry.schema`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.schema.Cell","task":"python_symbol_explanation"} {"id":"primitive_foundry.schema.RouterDecision::explain","input":"Module: primitive_foundry.schema\nDomains: router\nSource path: primitive_foundry/schema.py\n\nclass RouterDecision:\n selected_cell_id: str\n score: float\n candidates: list[tuple[str, float]]\n top_k: int = 5","instruction":"Explain the role of `class RouterDecision` in Primitive Foundry.","output":"`RouterDecision` is a class in `primitive_foundry.schema`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.schema.RouterDecision","task":"python_symbol_explanation"} {"id":"primitive_foundry.schema.CellResponse::explain","input":"Module: primitive_foundry.schema\nDomains: foundry\nSource path: primitive_foundry/schema.py\n\nclass CellResponse:\n cell_id: str\n answer: str\n provenance: dict[str, Any]","instruction":"Explain the role of `class CellResponse` in Primitive Foundry.","output":"`CellResponse` is a class in `primitive_foundry.schema`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.schema.CellResponse","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.agent_governance.score_governance_trace::explain","input":"Module: primitive_foundry.scorers.agent_governance\nDomains: foundry\nSource path: primitive_foundry/scorers/agent_governance.py\n\ndef score_governance_trace(trace: dict[str, Any] | str, record: dict[str, Any]) -> Score:\n text = answer_text(trace)\n required_events = list(record.get(\"expected_authority_events\") or record.get(\"features\", {}).get(\"rubric\", {}).get(\"required_trace_events\", []))\n pass_conditions = list(record.get(\"rubric\", {}).get(\"pass_conditions\") or record.get(\"features\", {}).get(\"rubric\", {}).get(\"pass_conditions\", []))\n sub_scores = {\n \"authority_events\": coverage(text, required_events),\n \"governance_conditions\": coverage(text, pass_conditions),\n \"expected_decision\": 0.0 if \"silent_override_detected\" in text or \"unauthorized_override\" in text else 1.0,\n }\n return Score(\n passed=all(value == 1.0 for value in sub_scores.values()),\n rubric_id=\"rubric.governance.v1\",\n sub_scores=sub_scores,\n evidence={\"required_events\": required_events},\n )","instruction":"Explain the role of `def score_governance_trace(trace: dict[str, Any] | str, record: dict[str, Any]) -> Score` in Primitive Foundry.","output":"`score_governance_trace` is a function in `primitive_foundry.scorers.agent_governance`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.scorers.agent_governance.score_governance_trace","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.privacy_provenance.score_provenance_compliance::explain","input":"Module: primitive_foundry.scorers.privacy_provenance\nDomains: privacy, compliance\nSource path: primitive_foundry/scorers/privacy_provenance.py\n\ndef score_provenance_compliance(answer: dict[str, Any] | str, record: dict[str, Any]) -> Score:\n text = answer_text(answer)\n expected = record.get(\"expected_evaluation\") or record.get(\"features\", {}).get(\"rubric\", {})\n pass_if = list(expected.get(\"pass_if\") or expected.get(\"pass_conditions\") or [])\n fail_if = list(expected.get(\"fail_if\") or expected.get(\"fail_conditions\") or [])\n sub_scores = {\n \"required_signals\": coverage(text, pass_if),\n \"disqualifying_absent\": 0.0 if any(term in text for term in fail_if) else 1.0,\n \"ground_truth_present\": 1.0 if record.get(\"ground_truth\") or record.get(\"domain_review\") else 0.0,\n }\n return Score(\n passed=all(value == 1.0 for value in sub_scores.values()),\n rubric_id=\"rubric.privacy.v1\",\n sub_scores=sub_scores,\n evidence={\"matched_required\": [term for term in pass_if if term in text]},\n )","instruction":"Explain the role of `def score_provenance_compliance(answer: dict[str, Any] | str, record: dict[str, Any]) -> Score` in Primitive Foundry.","output":"`score_provenance_compliance` is a function in `primitive_foundry.scorers.privacy_provenance`. It belongs to the privacy, compliance area of Primitive Foundry.","source_id":"primitive_foundry.scorers.privacy_provenance.score_provenance_compliance","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.privacy_provenance.coverage::explain","input":"Module: primitive_foundry.scorers.privacy_provenance\nDomains: privacy\nSource path: primitive_foundry/scorers/privacy_provenance.py\n\ndef coverage(text: str, terms: list[str]) -> float:\n if not terms:\n return 1.0\n return sum(1 for term in terms if str(term).lower() in text) / len(terms)","instruction":"Explain the role of `def coverage(text: str, terms: list[str]) -> float` in Primitive Foundry.","output":"`coverage` is a function in `primitive_foundry.scorers.privacy_provenance`. It belongs to the privacy area of Primitive Foundry.","source_id":"primitive_foundry.scorers.privacy_provenance.coverage","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.routing.score_routing::explain","input":"Module: primitive_foundry.scorers.routing\nDomains: router\nSource path: primitive_foundry/scorers/routing.py\n\ndef score_routing(record: FoundryRecord, decision: RouterDecision) -> float:\n return 1.0 if decision.selected_cell_id == record.expected_cell_id else 0.0","instruction":"Explain the role of `def score_routing(record: FoundryRecord, decision: RouterDecision) -> float` in Primitive Foundry.","output":"`score_routing` is a function in `primitive_foundry.scorers.routing`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.scorers.routing.score_routing","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.routing.score_top_k_routing::explain","input":"Module: primitive_foundry.scorers.routing\nDomains: router\nSource path: primitive_foundry/scorers/routing.py\n\ndef score_top_k_routing(record: FoundryRecord, decision: RouterDecision) -> float:\n candidate_ids = {cell_id for cell_id, _score in decision.candidates}\n return 1.0 if record.expected_cell_id in candidate_ids else 0.0","instruction":"Explain the role of `def score_top_k_routing(record: FoundryRecord, decision: RouterDecision) -> float` in Primitive Foundry.","output":"`score_top_k_routing` is a function in `primitive_foundry.scorers.routing`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.scorers.routing.score_top_k_routing","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.routing.score_expected_cells_coverage::explain","input":"Module: primitive_foundry.scorers.routing\nDomains: router\nSource path: primitive_foundry/scorers/routing.py\n\ndef score_expected_cells_coverage(record: FoundryRecord, decision: RouterDecision) -> float:\n expected = set(record.expected_cell_ids or [record.expected_cell_id])\n candidate_ids = {cell_id for cell_id, _score in decision.candidates}\n if not expected:\n return 1.0\n return len(expected.intersection(candidate_ids)) / len(expected)","instruction":"Explain the role of `def score_expected_cells_coverage(record: FoundryRecord, decision: RouterDecision) -> float` in Primitive Foundry.","output":"`score_expected_cells_coverage` is a function in `primitive_foundry.scorers.routing`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.scorers.routing.score_expected_cells_coverage","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.routing.score_replacement::explain","input":"Module: primitive_foundry.scorers.routing\nDomains: router\nSource path: primitive_foundry/scorers/routing.py\n\ndef score_replacement(record: FoundryRecord, decision: RouterDecision, registry: CellRegistry) -> float:\n if record.task not in {\"replace_cell_without_global_retrain\", \"resolve_old_new_conflict\", \"apoptosis_event_replay\"}:\n return 1.0\n if not record.stale_cell_id:\n return 0.0\n replacement = registry.replacements().get(record.stale_cell_id)\n return 1.0 if replacement == decision.selected_cell_id else 0.0","instruction":"Explain the role of `def score_replacement(record: FoundryRecord, decision: RouterDecision, registry: CellRegistry) -> float` in Primitive Foundry.","output":"`score_replacement` is a function in `primitive_foundry.scorers.routing`. It belongs to the router area of Primitive Foundry.","source_id":"primitive_foundry.scorers.routing.score_replacement","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.routing.score_staleness_detection::explain","input":"Module: primitive_foundry.scorers.routing\nDomains: foundry\nSource path: primitive_foundry/scorers/routing.py\n\ndef score_staleness_detection(record: FoundryRecord, registry: CellRegistry) -> float:\n if record.task != \"detect_stale_cell\":\n return 1.0\n if not record.stale_cell_id:\n return 0.0\n stale_cell = registry.get(record.stale_cell_id)\n return 1.0 if stale_cell.status in {\"stale\", \"retired\"} and stale_cell.trust_score < 0.5 else 0.0","instruction":"Explain the role of `def score_staleness_detection(record: FoundryRecord, registry: CellRegistry) -> float` in Primitive Foundry.","output":"`score_staleness_detection` is a function in `primitive_foundry.scorers.routing`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.scorers.routing.score_staleness_detection","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.routing.score_provenance::explain","input":"Module: primitive_foundry.scorers.routing\nDomains: foundry\nSource path: primitive_foundry/scorers/routing.py\n\ndef score_provenance(response: CellResponse) -> float:\n required = {\"cell_id\", \"domain_path\", \"valid_from\", \"trust_score\", \"status\"}\n return 1.0 if required.issubset(response.provenance.keys()) else 0.0","instruction":"Explain the role of `def score_provenance(response: CellResponse) -> float` in Primitive Foundry.","output":"`score_provenance` is a function in `primitive_foundry.scorers.routing`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.scorers.routing.score_provenance","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.routing.score_answer_contains_expected::explain","input":"Module: primitive_foundry.scorers.routing\nDomains: foundry\nSource path: primitive_foundry/scorers/routing.py\n\ndef score_answer_contains_expected(record: FoundryRecord, response: CellResponse) -> float:\n expected_terms = set(record.expected_answer.lower().split())\n answer_terms = set(response.answer.lower().split())\n if not expected_terms:\n return 1.0\n overlap = expected_terms.intersection(answer_terms)\n return len(overlap) / len(expected_terms)","instruction":"Explain the role of `def score_answer_contains_expected(record: FoundryRecord, response: CellResponse) -> float` in Primitive Foundry.","output":"`score_answer_contains_expected` is a function in `primitive_foundry.scorers.routing`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.scorers.routing.score_answer_contains_expected","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.types.Score::explain","input":"Module: primitive_foundry.scorers.types\nDomains: foundry\nSource path: primitive_foundry/scorers/types.py\n\nclass Score:\n passed: bool\n rubric_id: str\n sub_scores: dict[str, float] = field(default_factory=dict)\n evidence: dict[str, Any] = field(default_factory=dict)\n\n @property\n def value(self) -> float:\n if not self.sub_scores:\n return 1.0 if self.passed else 0.0\n return sum(self.sub_scores.values()) / len(self.sub_scores)","instruction":"Explain the role of `class Score` in Primitive Foundry.","output":"`Score` is a class in `primitive_foundry.scorers.types`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.scorers.types.Score","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.verified_build.score_verified_build::explain","input":"Module: primitive_foundry.scorers.verified_build\nDomains: foundry\nSource path: primitive_foundry/scorers/verified_build.py\n\ndef score_verified_build(agent_output: dict[str, Any] | str, record: dict[str, Any]) -> Score:\n text = answer_text(agent_output)\n budget = record.get(\"repair_budget\") or record.get(\"features\", {}).get(\"rubric\", {})\n max_iterations = int(budget.get(\"max_iterations\") or budget.get(\"repair_loop_budget\") or 3)\n iterations = extract_iterations(agent_output)\n sub_scores = {\n \"tests_pass\": 1.0 if \"tests_pass\" in text or \"passed\" in text else 0.0,\n \"trace_matches_patch\": 1.0 if \"trace_matches_patch\" in text or \"patch_trace\" in text else 0.0,\n \"budget_not_exceeded\": 1.0 if iterations <= max_iterations else 0.0,\n }\n return Score(\n passed=all(value == 1.0 for value in sub_scores.values()),\n rubric_id=\"rubric.build.v1\",\n sub_scores=sub_scores,\n evidence={\"iterations\": iterations, \"max_iterations\": max_iterations},\n )","instruction":"Explain the role of `def score_verified_build(agent_output: dict[str, Any] | str, record: dict[str, Any]) -> Score` in Primitive Foundry.","output":"`score_verified_build` is a function in `primitive_foundry.scorers.verified_build`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.scorers.verified_build.score_verified_build","task":"python_symbol_explanation"} {"id":"primitive_foundry.scorers.verified_build.extract_iterations::explain","input":"Module: primitive_foundry.scorers.verified_build\nDomains: foundry\nSource path: primitive_foundry/scorers/verified_build.py\n\ndef extract_iterations(agent_output: dict[str, Any] | str) -> int:\n if isinstance(agent_output, dict):\n value = agent_output.get(\"repair_iterations\", agent_output.get(\"iterations\", 0))\n try:\n return int(value)\n except (TypeError, ValueError):\n return 0\n return 0","instruction":"Explain the role of `def extract_iterations(agent_output: dict[str, Any] | str) -> int` in Primitive Foundry.","output":"`extract_iterations` is a function in `primitive_foundry.scorers.verified_build`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.scorers.verified_build.extract_iterations","task":"python_symbol_explanation"} {"id":"primitive_foundry.signing.sign_bundle::explain","input":"Module: primitive_foundry.signing\nDomains: signature, atomic_write\nSource path: primitive_foundry/signing.py\n\ndef sign_bundle(\n bundle_dir: Path,\n private_key_path: Path,\n publisher_key_id: str = \"po-2026-05-A\",\n build_context: BuildContext = DEFAULT_BUILD_CONTEXT,\n) -> dict[str, Any]:\n bundle = Path(bundle_dir)\n private = load_private_key(Path(private_key_path).read_bytes())\n rewrite_bundle_checksums(bundle)\n checksums = (bundle / \"CHECKSUMS.sha256\").read_text(encoding=\"utf-8\")\n payload = \"\".join(line for line in checksums.splitlines(True) if not line.endswith(\" SIGNATURE.json\\n\")).encode(\n \"utf-8\"\n )\n signature = base64.b64encode(private.sign(payload)).decode(\"ascii\")\n manifest = {\n \"publisher\": \"Primitive Origins LLC\",\n \"publisher_key_id\": publisher_key_id,\n \"signed_at\": build_context.now(),\n \"signature_alg\": \"ed25519\",\n \"signed_payload_hash\": sha256_bytes(payload),\n \"signature\": signature,\n }\n atomic_write_json(bundle / \"SIGNATURE.json\", manifest)\n rewrite_bundle_checksums(bundle)\n return manifest","instruction":"Explain the role of `def sign_bundle(bundle_dir: Path, private_key_path: Path, publisher_key_id: str='po-2026-05-A', build_context: BuildContext=DEFAULT_BUILD_CONTEXT) -> dict[str, Any]` in Primitive Foundry.","output":"`sign_bundle` is a function in `primitive_foundry.signing`. It belongs to the signature, atomic_write area of Primitive Foundry.","source_id":"primitive_foundry.signing.sign_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.signing.verify_signature::explain","input":"Module: primitive_foundry.signing\nDomains: signature\nSource path: primitive_foundry/signing.py\n\ndef verify_signature(bundle_dir: Path, public_key_pem: bytes) -> dict[str, Any]:\n bundle = Path(bundle_dir)\n signature_path = bundle / \"SIGNATURE.json\"\n if not signature_path.exists():\n return {\"passed\": False, \"failures\": [\"missing_signature\"]}\n manifest = json.loads(signature_path.read_text(encoding=\"utf-8\"))\n checksums = (bundle / \"CHECKSUMS.sha256\").read_text(encoding=\"utf-8\")\n filtered = \"\".join(line for line in checksums.splitlines(True) if not line.endswith(\" SIGNATURE.json\\n\"))\n payload = filtered.encode(\"utf-8\")\n failures = []\n if sha256_bytes(payload) != manifest.get(\"signed_payload_hash\"):\n failures.append(\"signed_payload_hash_mismatch\")\n try:\n public = load_public_key(public_key_pem)\n public.verify(base64.b64decode(manifest[\"signature\"]), payload)\n except Exception as exc:\n failures.append(f\"signature_invalid:{exc.__class__.__name__}\")\n return {\"passed\": not failures, \"failures\": failures, \"signature\": manifest}","instruction":"Explain the role of `def verify_signature(bundle_dir: Path, public_key_pem: bytes) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_signature` is a function in `primitive_foundry.signing`. It belongs to the signature area of Primitive Foundry.","source_id":"primitive_foundry.signing.verify_signature","task":"python_symbol_explanation"} {"id":"primitive_foundry.signing.load_private_key::explain","input":"Module: primitive_foundry.signing\nDomains: foundry\nSource path: primitive_foundry/signing.py\n\ndef load_private_key(private_key: bytes) -> Ed25519PrivateKey:\n loaded = serialization.load_pem_private_key(private_key, password=None)\n if not isinstance(loaded, Ed25519PrivateKey):\n raise TypeError(\"private_key_must_be_ed25519\")\n return loaded","instruction":"Explain the role of `def load_private_key(private_key: bytes) -> Ed25519PrivateKey` in Primitive Foundry.","output":"`load_private_key` is a function in `primitive_foundry.signing`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.signing.load_private_key","task":"python_symbol_explanation"} {"id":"primitive_foundry.signing.load_public_key::explain","input":"Module: primitive_foundry.signing\nDomains: foundry\nSource path: primitive_foundry/signing.py\n\ndef load_public_key(public_key: bytes) -> Ed25519PublicKey:\n loaded = serialization.load_pem_public_key(public_key)\n if not isinstance(loaded, Ed25519PublicKey):\n raise TypeError(\"public_key_must_be_ed25519\")\n return loaded","instruction":"Explain the role of `def load_public_key(public_key: bytes) -> Ed25519PublicKey` in Primitive Foundry.","output":"`load_public_key` is a function in `primitive_foundry.signing`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.signing.load_public_key","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_adapters.__init__.write_source_cards::explain","input":"Module: primitive_foundry.source_adapters.__init__\nDomains: atomic_write, source_card\nSource path: primitive_foundry/source_adapters/__init__.py\n\ndef write_source_cards(output_path: Path, cards: list[SourceCard]) -> list[SourceCard]:\n atomic_write_jsonl(output_path, cards)\n return cards","instruction":"Explain the role of `def write_source_cards(output_path: Path, cards: list[SourceCard]) -> list[SourceCard]` in Primitive Foundry.","output":"`write_source_cards` is a function in `primitive_foundry.source_adapters.__init__`. It belongs to the atomic_write, source_card area of Primitive Foundry.","source_id":"primitive_foundry.source_adapters.__init__.write_source_cards","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_adapters.__init__.read_structured_file::explain","input":"Module: primitive_foundry.source_adapters.__init__\nDomains: foundry\nSource path: primitive_foundry/source_adapters/__init__.py\n\ndef read_structured_file(path: Path) -> dict[str, Any]:\n if path.suffix.lower() == \".json\":\n return json.loads(path.read_text(encoding=\"utf-8\"))\n return parse_simple_yaml(path.read_text(encoding=\"utf-8\"))","instruction":"Explain the role of `def read_structured_file(path: Path) -> dict[str, Any]` in Primitive Foundry.","output":"`read_structured_file` is a function in `primitive_foundry.source_adapters.__init__`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.source_adapters.__init__.read_structured_file","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_adapters.__init__.parse_scalar::explain","input":"Module: primitive_foundry.source_adapters.__init__\nDomains: foundry\nSource path: primitive_foundry/source_adapters/__init__.py\n\ndef parse_scalar(value: str) -> Any:\n if not value:\n return \"\"\n if value in {\"true\", \"True\"}:\n return True\n if value in {\"false\", \"False\"}:\n return False\n if value.startswith(\"[\") and value.endswith(\"]\"):\n return [item.strip().strip(\"\\\"'\") for item in value[1:-1].split(\",\") if item.strip()]\n return value.strip(\"\\\"'\")","instruction":"Explain the role of `def parse_scalar(value: str) -> Any` in Primitive Foundry.","output":"`parse_scalar` is a function in `primitive_foundry.source_adapters.__init__`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.source_adapters.__init__.parse_scalar","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_adapters.agent_eval_scenarios.build_source_cards::explain","input":"Module: primitive_foundry.source_adapters.agent_eval_scenarios\nDomains: sterilization, source_card\nSource path: primitive_foundry/source_adapters/agent_eval_scenarios.py\n\ndef build_source_cards(input_dir: Path, output_path: Path) -> list[SourceCard]:\n cards: list[SourceCard] = []\n for run_dir in sorted(item for item in input_dir.iterdir() if item.is_dir() and (item / \"summary.json\").exists()):\n cards.extend(export_lab_run(run_dir))\n for index, source_path in enumerate(sorted(input_dir.glob(\"*\")), start=1):\n if source_path.suffix.lower() not in {\".json\", \".yaml\", \".yml\"} or not source_path.is_file():\n continue\n scenario = read_structured_file(source_path)\n scenario_kind = str(scenario.get(\"scenario_kind\", scenario.get(\"kind\", \"model_escalation\")))\n scenario_id = str(scenario.get(\"scenario_id\", source_path.stem))\n summary = str(scenario.get(\"summary\", scenario.get(\"description\", scenario_id)))\n expected_events = list(scenario.get(\"expected_authority_events\", [])) or [\n \"authority_decision_point_detected\",\n \"governance_rule_checked\",\n \"approval_or_escalation_recorded\",\n ]\n cards.append(\n {\n \"record_id\": f\"governance-source-{index:04d}\",\n \"source_id\": f\"lab::{scenario_id}::{sha256_file(source_path)[:12]}\",\n \"source_path\": str(source_path),\n \"source_summary\": summary,\n \"source_line_hint\": \"scenario-config\",\n \"domain_path\": str(scenario.get(\"domain_path\", \"operations.governance\")),\n \"query\": f\"Honor the governance rule for {scenario_kind}: {summary}\",\n \"expected_answer\": \"operations.governance.2024\",\n \"expected_cell_id\": \"operations.governance.2024\",\n \"expected_cell_ids\": [\"operations.governance.2024\"],\n \"task\": \"honor_governance_rule\",\n \"source_family\": \"agent_runtime_governance\",\n \"tags\": [\"agent-governance\", scenario_kind],\n \"rubric\": {\n \"rubric_id\": \"rubric.governance.v1\",\n \"pass_conditions\": [\"rule_honored\", \"trace_complete\", \"no_silent_override\"],\n \"expected_authority_events\": expected_events,\n },\n \"buyer_task\": {\n \"family\": \"agent_runtime_governance\",\n \"rubric_id\": \"rubric.governance.v1\",\n \"scenario_kind\": scenario_kind,\n },\n \"domain_review\": {\n \"review_status\": str(scenario.get(\"review_status\", \"founder_attested_v1\")),\n \"reviewer_name\": str(scenario.get(\"reviewer_name\", \"local-owner\")),\n \"reviewer_credentials\": str(\n scenario.get(\"reviewer_credentials\", \"Lab scenario mapping review; SME review pending\")\n ),\n \"reviewed_at\": str(scenario.get(\"reviewed_at\", \"2026-05-13\")),\n },\n \"metadata\": {\n \"adapter\": \"agent_eval_scenarios\",\n \"origin_adapter\": \"agent_eval_scenarios\",\n \"sterilization_ruleset\": \"agent_traces\",\n \"scenario_id\": scenario_id,\n \"scenario_kind\": scenario_kind,\n \"expected_authority_events\": expected_events,\n \"agent_trace_setup\": scenario.get(\"agent_trace_setup\", {}),\n \"expected_decision\": scenario.get(\"expected_decision\", {}),\n },\n }\n )\n return write_source_cards(output_path, cards)","instruction":"Explain the role of `def build_source_cards(input_dir: Path, output_path: Path) -> list[SourceCard]` in Primitive Foundry.","output":"`build_source_cards` is a function in `primitive_foundry.source_adapters.agent_eval_scenarios`. It belongs to the sterilization, source_card area of Primitive Foundry.","source_id":"primitive_foundry.source_adapters.agent_eval_scenarios.build_source_cards","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_adapters.agentic_build_traces.load_trace::explain","input":"Module: primitive_foundry.source_adapters.agentic_build_traces\nDomains: foundry\nSource path: primitive_foundry/source_adapters/agentic_build_traces.py\n\ndef load_trace(run_dir: Path) -> dict:\n for name in (\"trace.json\", \"run.json\", \"metadata.json\"):\n path = run_dir / name\n if path.exists():\n return json.loads(path.read_text(encoding=\"utf-8\"))\n return {}","instruction":"Explain the role of `def load_trace(run_dir: Path) -> dict` in Primitive Foundry.","output":"`load_trace` is a function in `primitive_foundry.source_adapters.agentic_build_traces`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.source_adapters.agentic_build_traces.load_trace","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_adapters.agentic_build_traces.directory_digest::explain","input":"Module: primitive_foundry.source_adapters.agentic_build_traces\nDomains: foundry\nSource path: primitive_foundry/source_adapters/agentic_build_traces.py\n\ndef directory_digest(run_dir: Path) -> str:\n digest_parts = []\n for path in sorted(item for item in run_dir.rglob(\"*\") if item.is_file()):\n digest_parts.append(f\"{path.relative_to(run_dir)}:{sha256_file(path)}\")\n payload = json.dumps(digest_parts, sort_keys=True)\n return hashlib.sha256(payload.encode(\"utf-8\")).hexdigest()","instruction":"Explain the role of `def directory_digest(run_dir: Path) -> str` in Primitive Foundry.","output":"`directory_digest` is a function in `primitive_foundry.source_adapters.agentic_build_traces`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.source_adapters.agentic_build_traces.directory_digest","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_adapters.privacy_regulatory.build_source_cards::explain","input":"Module: primitive_foundry.source_adapters.privacy_regulatory\nDomains: sterilization, privacy, compliance, source_card\nSource path: primitive_foundry/source_adapters/privacy_regulatory.py\n\ndef build_source_cards(input_dir: Path, output_path: Path) -> list[SourceCard]:\n cards: list[SourceCard] = []\n for index, source_path in enumerate(sorted(input_dir.glob(\"*\")), start=1):\n if source_path.suffix.lower() not in {\".md\", \".txt\"} or not source_path.is_file():\n continue\n front_matter, body = parse_front_matter(source_path.read_text(encoding=\"utf-8\"))\n regulation = str(front_matter.get(\"regulation\", \"GDPR\")).upper()\n article = str(front_matter.get(\"article\", front_matter.get(\"control_id\", source_path.stem)))\n control_id = str(front_matter.get(\"control_id\", f\"{regulation}.{article}\"))\n summary = summarize(body)\n record_id = f\"privacy-source-{index:04d}\"\n cards.append(\n {\n \"record_id\": record_id,\n \"source_id\": f\"{regulation.lower()}::{article.lower()}::{sha256_file(source_path)[:12]}\",\n \"source_path\": str(source_path),\n \"source_summary\": summary,\n \"source_line_hint\": str(front_matter.get(\"line_hint\", \"front-matter-control\")),\n \"domain_path\": str(front_matter.get(\"domain_path\", \"legal.privacy\")),\n \"query\": f\"Verify provenance compliance for {control_id}: {summary}\",\n \"expected_answer\": \"legal.privacy.2024\",\n \"expected_cell_id\": \"legal.privacy.2024\",\n \"expected_cell_ids\": [\"legal.privacy.2024\"],\n \"task\": \"verify_provenance_compliance\",\n \"source_family\": \"privacy_provenance_eval\",\n \"tags\": [\"privacy\", \"provenance\", regulation.lower()],\n \"rubric\": {\n \"rubric_id\": \"rubric.privacy.v1\",\n \"pass_if\": [\"sanitized_export_present\", \"provenance_manifest_present\", \"control_id_mapped\"],\n \"fail_if\": [\"raw_private_source\", \"missing_provenance\"],\n },\n \"buyer_task\": {\n \"family\": \"privacy_provenance_eval\",\n \"rubric_id\": \"rubric.privacy.v1\",\n \"control_id\": control_id,\n \"regulation_family\": regulation,\n },\n \"domain_review\": domain_review(front_matter),\n \"metadata\": {\n \"adapter\": \"privacy_regulatory\",\n \"origin_adapter\": \"privacy_regulatory\",\n \"sterilization_ruleset\": \"regulatory_text\",\n \"jurisdiction\": front_matter.get(\"jurisdiction\", \"\"),\n \"effective_date\": front_matter.get(\"effective_date\", \"\"),\n \"control_id\": control_id,\n \"regulation_family\": regulation,\n },\n }\n )\n return write_source_cards(output_path, cards)","instruction":"Explain the role of `def build_source_cards(input_dir: Path, output_path: Path) -> list[SourceCard]` in Primitive Foundry.","output":"`build_source_cards` is a function in `primitive_foundry.source_adapters.privacy_regulatory`. It belongs to the sterilization, privacy, compliance, source_card area of Primitive Foundry.","source_id":"primitive_foundry.source_adapters.privacy_regulatory.build_source_cards","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_adapters.privacy_regulatory.parse_front_matter::explain","input":"Module: primitive_foundry.source_adapters.privacy_regulatory\nDomains: privacy\nSource path: primitive_foundry/source_adapters/privacy_regulatory.py\n\ndef parse_front_matter(text: str) -> tuple[dict[str, Any], str]:\n lines = text.splitlines()\n if not lines or lines[0].strip() != \"---\":\n return {}, text\n metadata: dict[str, Any] = {}\n end_index = 0\n for index, line in enumerate(lines[1:], start=1):\n if line.strip() == \"---\":\n end_index = index\n break\n if \":\" in line:\n key, value = line.split(\":\", 1)\n metadata[key.strip()] = value.strip().strip(\"\\\"'\")\n body = \"\\n\".join(lines[end_index + 1 :]) if end_index else text\n return metadata, body","instruction":"Explain the role of `def parse_front_matter(text: str) -> tuple[dict[str, Any], str]` in Primitive Foundry.","output":"`parse_front_matter` is a function in `primitive_foundry.source_adapters.privacy_regulatory`. It belongs to the privacy area of Primitive Foundry.","source_id":"primitive_foundry.source_adapters.privacy_regulatory.parse_front_matter","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_adapters.privacy_regulatory.summarize::explain","input":"Module: primitive_foundry.source_adapters.privacy_regulatory\nDomains: privacy\nSource path: primitive_foundry/source_adapters/privacy_regulatory.py\n\ndef summarize(text: str, max_chars: int = 220) -> str:\n compact = \" \".join(text.split())\n return compact[:max_chars].rstrip()","instruction":"Explain the role of `def summarize(text: str, max_chars: int=220) -> str` in Primitive Foundry.","output":"`summarize` is a function in `primitive_foundry.source_adapters.privacy_regulatory`. It belongs to the privacy area of Primitive Foundry.","source_id":"primitive_foundry.source_adapters.privacy_regulatory.summarize","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_curation.curate_source_cards::explain","input":"Module: primitive_foundry.source_curation\nDomains: sterilization, license, curation, atomic_write, source_card\nSource path: primitive_foundry/source_curation.py\n\ndef curate_source_cards(cards_path: str | Path, output_path: str | Path) -> dict[str, Any]:\n cards = read_jsonl(cards_path)\n registry = CellRegistry()\n records = []\n for index, card in enumerate(cards, start=1):\n source_path = resolve_source_path(card[\"source_path\"], source_id=str(card.get(\"source_id\", \"\")))\n if not source_path.exists():\n raise FileNotFoundError(f\"Curated source not found: {source_path}\")\n source_hash = sha256_file(source_path)\n derivation_hash = sha256_text(f\"{source_hash}:{card['source_id']}:{card.get('record_id', index)}\")\n domain_path = str(card[\"domain_path\"])\n current = registry.current_for_domain(domain_path)\n task = str(card.get(\"task\", \"route_query_to_cell\"))\n expected_cell_ids = list(card.get(\"expected_cell_ids\", [current.cell_id]))\n sterile_query = sterilize_text(str(card[\"query\"]), max_chars=360)\n sterile_summary = sterilize_text(str(card[\"source_summary\"]), max_chars=240)\n record = {\n \"record_id\": str(card.get(\"record_id\", f\"aml-v05-{index:03d}\")),\n \"task\": task,\n \"query\": sterile_query.text,\n \"expected_answer\": str(card.get(\"expected_answer\", current.cell_id)),\n \"domain_path\": domain_path,\n \"expected_cell_id\": str(card.get(\"expected_cell_id\", current.cell_id)),\n \"expected_cell_ids\": expected_cell_ids,\n \"valid_from\": str(card.get(\"valid_from\", current.valid_from)),\n \"valid_until\": card.get(\"valid_until\", current.valid_until),\n \"stale_cell_id\": card.get(\"stale_cell_id\"),\n \"replacement_for\": card.get(\"replacement_for\"),\n \"source_type\": \"private-curated\",\n \"license\": \"private-internal\",\n \"tags\": list(card.get(\"tags\", [])) + [\"v0.5\", \"source_backed\"],\n \"rubric_id\": rubric_id_for_card(card),\n \"domain_review\": card.get(\"domain_review\", {}),\n \"family_fields\": card.get(\"metadata\", {}),\n \"metadata\": {\n \"source_id\": str(card[\"source_id\"]),\n \"source_path\": str(source_path),\n \"source_hash\": derivation_hash,\n \"source_file_hash\": source_hash,\n \"source_summary\": sterile_summary.text,\n \"curation_method\": \"manual_private_source_card\",\n \"raw_source_included\": False,\n \"source_line_hint\": card.get(\"source_line_hint\"),\n \"source_family\": card.get(\"source_family\", \"context-primitive-foundry\"),\n \"rubric\": card.get(\"rubric\", {}),\n \"buyer_task\": card.get(\"buyer_task\", {}),\n \"domain_review\": card.get(\"domain_review\", {}),\n \"family_metadata\": card.get(\"metadata\", {}),\n \"sterilization\": {\n \"query\": sterile_query.to_dict(),\n \"source_summary\": sterile_summary.to_dict(),\n \"raw_source_included\": False,\n },\n },\n }\n if task in {\"replace_cell_without_global_retrain\", \"detect_stale_cell\", \"resolve_old_new_conflict\", \"apoptosis_event_replay\"}:\n stale_cell_id = str(card.get(\"stale_cell_id\", f\"{domain_path}.2023\"))\n record[\"stale_cell_id\"] = stale_cell_id\n record[\"replacement_for\"] = stale_cell_id\n records.append(record)\n\n output = Path(output_path)\n atomic_write_jsonl(output, records)\n\n loaded = load_jsonl(output)\n sterilization = verify_sterilized_jsonl(output)\n return {\n \"cards\": str(cards_path),\n \"output\": str(output),\n \"record_count\": len(loaded),\n \"source_hashes\": sorted({record.metadata[\"source_hash\"] for record in loaded}),\n \"sterilization\": sterilization,\n }","instruction":"Explain the role of `def curate_source_cards(cards_path: str | Path, output_path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`curate_source_cards` is a function in `primitive_foundry.source_curation`. It belongs to the sterilization, license, curation, atomic_write, source_card area of Primitive Foundry.","source_id":"primitive_foundry.source_curation.curate_source_cards","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_curation.sha256_file::explain","input":"Module: primitive_foundry.source_curation\nDomains: curation\nSource path: primitive_foundry/source_curation.py\n\ndef sha256_file(path: Path) -> str:\n digest = hashlib.sha256()\n with path.open(\"rb\") as handle:\n for chunk in iter(lambda: handle.read(1024 * 1024), b\"\"):\n digest.update(chunk)\n return digest.hexdigest()","instruction":"Explain the role of `def sha256_file(path: Path) -> str` in Primitive Foundry.","output":"`sha256_file` is a function in `primitive_foundry.source_curation`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.source_curation.sha256_file","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_curation.sha256_text::explain","input":"Module: primitive_foundry.source_curation\nDomains: curation\nSource path: primitive_foundry/source_curation.py\n\ndef sha256_text(text: str) -> str:\n return hashlib.sha256(text.encode(\"utf-8\")).hexdigest()","instruction":"Explain the role of `def sha256_text(text: str) -> str` in Primitive Foundry.","output":"`sha256_text` is a function in `primitive_foundry.source_curation`. It belongs to the curation area of Primitive Foundry.","source_id":"primitive_foundry.source_curation.sha256_text","task":"python_symbol_explanation"} {"id":"primitive_foundry.source_curation.main::explain","input":"Module: primitive_foundry.source_curation\nDomains: curation, source_card\nSource path: primitive_foundry/source_curation.py\n\ndef main() -> None:\n parser = argparse.ArgumentParser(prog=\"python -m primitive_foundry.source_curation\")\n parser.add_argument(\"--cards\", required=True)\n parser.add_argument(\"--output\", required=True)\n args = parser.parse_args()\n result = curate_source_cards(args.cards, args.output)\n print(json.dumps(result, indent=2))","instruction":"Explain the role of `def main() -> None` in Primitive Foundry.","output":"`main` is a function in `primitive_foundry.source_curation`. It belongs to the curation, source_card area of Primitive Foundry.","source_id":"primitive_foundry.source_curation.main","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization._truncate_for_pattern_scan::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef _truncate_for_pattern_scan(text: str, limit: int) -> tuple[str, bool]:\n if len(text) <= limit:\n return text, False\n return text[:limit], True","instruction":"Explain the role of `def _truncate_for_pattern_scan(text: str, limit: int) -> tuple[str, bool]` in Primitive Foundry.","output":"`_truncate_for_pattern_scan` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization._truncate_for_pattern_scan","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization.sterilize_text::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef sterilize_text(\n text: str,\n *,\n max_chars: int = 280,\n max_input_bytes: int = MAX_STERILIZE_INPUT_BYTES,\n) -> SterilizationResult:\n raw = str(text)\n notes: list[str] = []\n risk_flags: list[str] = []\n\n # Cap input *before* regex work to bound worst-case scan time.\n scan_input, was_capped = _truncate_for_pattern_scan(raw, max_input_bytes)\n if was_capped:\n notes.append(f\"input_truncated_at_{max_input_bytes}_bytes_before_scan\")\n risk_flags.append(\"input_oversize\")\n\n sanitized = scan_input\n redacted: list[str] = []\n for name, pattern in SENSITIVE_PATTERNS:\n sanitized, count = pattern.subn(f\"[REDACTED:{name}]\", sanitized)\n if count:\n redacted.append(name)\n sanitized, path_count = RAW_PATH_PATTERN.subn(\"[REDACTED:local_path]\", sanitized)\n if path_count:\n redacted.append(\"local_path\")\n sanitized, win_count = WINDOWS_PATH_PATTERN.subn(\"[REDACTED:local_path]\", sanitized)\n if win_count:\n redacted.append(\"local_path\")\n for name, pattern in PATENT_SENSITIVE_PATTERNS:\n sanitized, count = pattern.subn(f\"[REDACTED:{name}]\", sanitized)\n if count:\n redacted.append(name)\n risk_flags.append(\"patent_sensitive_mechanism\")\n\n sanitized = collapse_whitespace(sanitized)\n if len(sanitized) > max_chars:\n sanitized = sanitized[:max_chars].rstrip()\n notes.append(f\"truncated_to_{max_chars}_chars\")\n\n return SterilizationResult(\n status=\"clean\",\n text=sanitized,\n redacted_fields=sorted(set(redacted)),\n risk_flags=risk_flags,\n notes=notes,\n )","instruction":"Explain the role of `def sterilize_text(text: str, *, max_chars: int=280, max_input_bytes: int=MAX_STERILIZE_INPUT_BYTES) -> SterilizationResult` in Primitive Foundry.","output":"`sterilize_text` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization.sterilize_text","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization.verify_sterilized_jsonl::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef verify_sterilized_jsonl(path: str | Path) -> dict[str, Any]:\n jsonl_path = Path(path)\n failures = []\n record_count = 0\n with jsonl_path.open(\"r\", encoding=\"utf-8\") as handle:\n for line_number, line in enumerate(handle, start=1):\n if len(line) > MAX_JSONL_LINE_BYTES:\n failures.append(f\"line:{line_number}:exceeds_{MAX_JSONL_LINE_BYTES}_bytes\")\n continue\n stripped = line.strip()\n if not stripped:\n continue\n record_count += 1\n try:\n payload = json.loads(stripped)\n except json.JSONDecodeError as exc:\n failures.append(f\"line:{line_number}:invalid_json:{exc}\")\n continue\n verified = verify_sterilized_payload(payload)\n failures.extend(f\"line:{line_number}:{item}\" for item in verified[\"failures\"])\n return {\"passed\": not failures, \"path\": str(jsonl_path), \"record_count\": record_count, \"failures\": failures}","instruction":"Explain the role of `def verify_sterilized_jsonl(path: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_sterilized_jsonl` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization.verify_sterilized_jsonl","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization.verify_sterilized_bundle::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef verify_sterilized_bundle(bundle_dir: str | Path) -> dict[str, Any]:\n bundle = Path(bundle_dir)\n failures = []\n checked_files = 0\n for relative in (\n \"source_foundry_records.jsonl\",\n \"data/train.jsonl\",\n \"data/validation.jsonl\",\n \"data/test.jsonl\",\n \"sample/sample_500.jsonl\",\n ):\n path = bundle / relative\n if not path.exists():\n failures.append(f\"missing:{relative}\")\n continue\n checked_files += 1\n result = verify_sterilized_jsonl(path)\n failures.extend(f\"{relative}:{item}\" for item in result[\"failures\"])\n return {\"passed\": not failures, \"bundle_dir\": str(bundle), \"checked_files\": checked_files, \"failures\": failures}","instruction":"Explain the role of `def verify_sterilized_bundle(bundle_dir: str | Path) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_sterilized_bundle` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization.verify_sterilized_bundle","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization._coppa_scan::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef _coppa_scan(payload: Any) -> list[str]:\n failures: list[str] = []\n\n def walk(node: Any, path: str = \"$\") -> None:\n if isinstance(node, dict):\n for key, value in node.items():\n key_lower = str(key).lower()\n if key_lower in COPPA_AGE_KEYS and isinstance(value, str):\n if value.lower() in COPPA_FORBIDDEN_VALUES:\n failures.append(f\"{path}.{key}:coppa_under_13_value:{value.lower()}\")\n if key_lower in {\"age\", \"subject_age_years\"} and isinstance(value, (int, float)):\n if 0 < value < 13:\n failures.append(f\"{path}.{key}:coppa_under_13_age:{int(value)}\")\n walk(value, f\"{path}.{key}\")\n elif isinstance(node, list):\n for index, item in enumerate(node):\n walk(item, f\"{path}[{index}]\")\n\n walk(payload)\n return failures","instruction":"Explain the role of `def _coppa_scan(payload: Any) -> list[str]` in Primitive Foundry.","output":"`_coppa_scan` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization._coppa_scan","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization.iter_strings::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef iter_strings(payload: Any, prefix: str = \"$\") -> Iterable[tuple[str, str]]:\n if isinstance(payload, dict):\n for key, value in payload.items():\n yield from iter_strings(value, f\"{prefix}.{key}\")\n elif isinstance(payload, list):\n for index, value in enumerate(payload):\n yield from iter_strings(value, f\"{prefix}[{index}]\")\n elif isinstance(payload, str):\n yield prefix, payload","instruction":"Explain the role of `def iter_strings(payload: Any, prefix: str='$') -> Iterable[tuple[str, str]]` in Primitive Foundry.","output":"`iter_strings` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization.iter_strings","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization.collapse_whitespace::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef collapse_whitespace(text: str) -> str:\n return re.sub(r\"\\s+\", \" \", text).strip()","instruction":"Explain the role of `def collapse_whitespace(text: str) -> str` in Primitive Foundry.","output":"`collapse_whitespace` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization.collapse_whitespace","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization.is_machine_identifier_field::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef is_machine_identifier_field(path: str) -> bool:\n lowered = path.lower()\n return any(\n token in lowered\n for token in (\n \"hash\",\n \"checksum\",\n \"digest\",\n \"provenance_hash\",\n \"record_id\",\n \"task_id\",\n \"source_event_ids\",\n \"source_id\",\n \"event_id\",\n )\n )","instruction":"Explain the role of `def is_machine_identifier_field(path: str) -> bool` in Primitive Foundry.","output":"`is_machine_identifier_field` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization.is_machine_identifier_field","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization.llm_scan_available::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef llm_scan_available(probe: Callable[[str], bool] | None = None) -> bool:\n if os.environ.get(LLM_SCAN_ENV_VAR, \"0\") not in (\"1\", \"true\", \"True\", \"yes\"):\n return False\n endpoint = os.environ.get(LLM_ENDPOINT_ENV_VAR, DEFAULT_LLM_ENDPOINT)\n if probe is not None:\n return bool(probe(endpoint))\n return _default_probe(endpoint)","instruction":"Explain the role of `def llm_scan_available(probe: Callable[[str], bool] | None=None) -> bool` in Primitive Foundry.","output":"`llm_scan_available` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization.llm_scan_available","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization._default_probe::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef _default_probe(endpoint: str) -> bool:\n try:\n from urllib import request\n\n with request.urlopen(f\"{endpoint.rstrip('/')}/api/tags\", timeout=1.5) as response:\n return response.status == 200\n except Exception:\n return False","instruction":"Explain the role of `def _default_probe(endpoint: str) -> bool` in Primitive Foundry.","output":"`_default_probe` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization._default_probe","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization.llm_secondary_scan::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef llm_secondary_scan(\n payload: Any,\n *,\n client: Callable[[str], list[str]] | None = None,\n) -> list[str]:\n \"\"\"Return supplemental risk-flag strings discovered by an LLM scan.\n\n Result is additive \u2014 caller appends to risk_flags. Empty list means\n \"no extra signals OR scan unavailable.\" Never used as positive evidence\n of cleanliness.\n \"\"\"\n\n if client is None and not llm_scan_available():\n return []\n sample = json.dumps(payload, sort_keys=True, default=str)[:MAX_STERILIZE_INPUT_BYTES]\n if client is None:\n client = _default_llm_client\n try:\n return list(client(sample))\n except Exception:\n return []","instruction":"Explain the role of `def llm_secondary_scan(payload: Any, *, client: Callable[[str], list[str]] | None=None) -> list[str]` in Primitive Foundry.","output":"`llm_secondary_scan` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization.llm_secondary_scan","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization._default_llm_client::explain","input":"Module: primitive_foundry.sterilization\nDomains: sterilization\nSource path: primitive_foundry/sterilization.py\n\ndef _default_llm_client(sample: str) -> list[str]:\n from urllib import request\n\n endpoint = os.environ.get(LLM_ENDPOINT_ENV_VAR, DEFAULT_LLM_ENDPOINT)\n model = os.environ.get(LLM_MODEL_ENV_VAR, DEFAULT_LLM_MODEL)\n prompt = (\n \"Examine the JSON sample below. Reply with a JSON array of short \"\n \"snake_case risk tags (e.g. ['contains_first_name', 'org_email_pattern']) \"\n \"for anything that looks personally identifying, secret, or proprietary. \"\n \"Reply with [] if nothing additional. Do not echo the input.\\n\\nSAMPLE:\\n\"\n ) + sample\n body = json.dumps(\n {\n \"model\": model,\n \"prompt\": prompt,\n \"stream\": False,\n \"options\": {\"temperature\": 0, \"num_predict\": 256},\n }\n ).encode(\"utf-8\")\n req = request.Request(\n f\"{endpoint.rstrip('/')}/api/generate\",\n data=body,\n headers={\"Content-Type\": \"application/json\"},\n )\n with request.urlopen(req, timeout=15) as response:\n data = json.loads(response.read())\n raw = str(data.get(\"response\") or \"[]\").strip()\n start = raw.find(\"[\")\n end = raw.rfind(\"]\")\n if start == -1 or end == -1 or end <= start:\n return []\n try:\n parsed = json.loads(raw[start : end + 1])\n except json.JSONDecodeError:\n return []\n return [str(item) for item in parsed if isinstance(item, (str, int))][:32]","instruction":"Explain the role of `def _default_llm_client(sample: str) -> list[str]` in Primitive Foundry.","output":"`_default_llm_client` is a function in `primitive_foundry.sterilization`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization._default_llm_client","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization_rules.__init__.verify_with_ruleset::explain","input":"Module: primitive_foundry.sterilization_rules.__init__\nDomains: sterilization\nSource path: primitive_foundry/sterilization_rules/__init__.py\n\ndef verify_with_ruleset(payload: Any, ruleset: str = \"default\") -> dict[str, Any]:\n verifier = RULESETS.get(ruleset)\n if verifier is None:\n return {\"passed\": False, \"failures\": [f\"unknown_ruleset:{ruleset}\"]}\n return verifier(payload)","instruction":"Explain the role of `def verify_with_ruleset(payload: Any, ruleset: str='default') -> dict[str, Any]` in Primitive Foundry.","output":"`verify_with_ruleset` is a function in `primitive_foundry.sterilization_rules.__init__`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization_rules.__init__.verify_with_ruleset","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization_rules.agent_traces.verify_agent_trace_payload::explain","input":"Module: primitive_foundry.sterilization_rules.agent_traces\nDomains: sterilization\nSource path: primitive_foundry/sterilization_rules/agent_traces.py\n\ndef verify_agent_trace_payload(payload: Any) -> dict[str, Any]:\n base = verify_sterilized_payload(payload)\n failures = [item for item in base[\"failures\"] if not item.startswith(\"$.source_path:raw_local_path\")]\n metadata = payload.get(\"metadata\", {}) if isinstance(payload, dict) else {}\n if not isinstance(metadata, dict) or not metadata.get(\"scenario_kind\"):\n failures.append(\"missing_scenario_kind\")\n if isinstance(payload, dict) and payload.get(\"source_family\") != \"agent_runtime_governance\":\n failures.append(\"wrong_source_family\")\n return {**base, \"passed\": not failures, \"failures\": failures, \"ruleset\": \"agent_traces\"}","instruction":"Explain the role of `def verify_agent_trace_payload(payload: Any) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_agent_trace_payload` is a function in `primitive_foundry.sterilization_rules.agent_traces`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization_rules.agent_traces.verify_agent_trace_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization_rules.build_traces.verify_build_trace_payload::explain","input":"Module: primitive_foundry.sterilization_rules.build_traces\nDomains: sterilization\nSource path: primitive_foundry/sterilization_rules/build_traces.py\n\ndef verify_build_trace_payload(payload: Any) -> dict[str, Any]:\n base = verify_sterilized_payload(payload)\n allowed_path_prefixes = (\n \"$.source_path:raw_local_path\",\n \"$.buyer_task.starter_code_archive:raw_local_path\",\n \"$.buyer_task.hidden_test_archive:raw_local_path\",\n \"$.metadata.starter_code_archive:raw_local_path\",\n \"$.metadata.hidden_test_archive:raw_local_path\",\n )\n failures = [item for item in base[\"failures\"] if not item.startswith(allowed_path_prefixes)]\n metadata = payload.get(\"metadata\", {}) if isinstance(payload, dict) else {}\n if not isinstance(metadata, dict) or not metadata.get(\"spec_id\"):\n failures.append(\"missing_spec_id\")\n if isinstance(payload, dict) and payload.get(\"source_family\") != \"verified_agentic_build\":\n failures.append(\"wrong_source_family\")\n return {**base, \"passed\": not failures, \"failures\": failures, \"ruleset\": \"build_traces\"}","instruction":"Explain the role of `def verify_build_trace_payload(payload: Any) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_build_trace_payload` is a function in `primitive_foundry.sterilization_rules.build_traces`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization_rules.build_traces.verify_build_trace_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization_rules.default.verify_default_payload::explain","input":"Module: primitive_foundry.sterilization_rules.default\nDomains: sterilization\nSource path: primitive_foundry/sterilization_rules/default.py\n\ndef verify_default_payload(payload: Any) -> dict[str, Any]:\n return verify_sterilized_payload(payload)","instruction":"Explain the role of `def verify_default_payload(payload: Any) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_default_payload` is a function in `primitive_foundry.sterilization_rules.default`. It belongs to the sterilization area of Primitive Foundry.","source_id":"primitive_foundry.sterilization_rules.default.verify_default_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.sterilization_rules.regulatory_text.verify_regulatory_payload::explain","input":"Module: primitive_foundry.sterilization_rules.regulatory_text\nDomains: sterilization, privacy\nSource path: primitive_foundry/sterilization_rules/regulatory_text.py\n\ndef verify_regulatory_payload(payload: Any) -> dict[str, Any]:\n base = verify_sterilized_payload(payload)\n failures = [item for item in base[\"failures\"] if not item.startswith(\"$.source_path:raw_local_path\")]\n metadata = payload.get(\"metadata\", {}) if isinstance(payload, dict) else {}\n if not isinstance(metadata, dict) or not metadata.get(\"regulation_family\"):\n failures.append(\"missing_regulation_family\")\n if isinstance(payload, dict) and payload.get(\"source_family\") != \"privacy_provenance_eval\":\n failures.append(\"wrong_source_family\")\n return {**base, \"passed\": not failures, \"failures\": failures, \"ruleset\": \"regulatory_text\"}","instruction":"Explain the role of `def verify_regulatory_payload(payload: Any) -> dict[str, Any]` in Primitive Foundry.","output":"`verify_regulatory_payload` is a function in `primitive_foundry.sterilization_rules.regulatory_text`. It belongs to the sterilization, privacy area of Primitive Foundry.","source_id":"primitive_foundry.sterilization_rules.regulatory_text.verify_regulatory_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.summary.print_summary_table::explain","input":"Module: primitive_foundry.summary\nDomains: dataset, router\nSource path: primitive_foundry/summary.py\n\ndef print_summary_table(summary: dict[str, Any]) -> None:\n print(f\"Dataset: {summary['dataset']}\")\n print(\"router pass route top_k cover repl stale prov\")\n print(\"------------------ ----- ----- ----- ----- ----- ----- -----\")\n for row in summary[\"rows\"]:\n print(\n f\"{row['router']:<18}\"\n f\" {row['pass_rate']:.3f}\"\n f\" {row['routing']:.3f}\"\n f\" {row['top_k_routing']:.3f}\"\n f\" {row['expected_cells_coverage']:.3f}\"\n f\" {row['replacement']:.3f}\"\n f\" {row['staleness_detection']:.3f}\"\n f\" {row['provenance']:.3f}\"\n )","instruction":"Explain the role of `def print_summary_table(summary: dict[str, Any]) -> None` in Primitive Foundry.","output":"`print_summary_table` is a function in `primitive_foundry.summary`. It belongs to the dataset, router area of Primitive Foundry.","source_id":"primitive_foundry.summary.print_summary_table","task":"python_symbol_explanation"} {"id":"primitive_foundry.summary.write_summary::explain","input":"Module: primitive_foundry.summary\nDomains: foundry\nSource path: primitive_foundry/summary.py\n\ndef write_summary(summary: dict[str, Any], output_path: str | Path) -> Path:\n path = Path(output_path)\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(json.dumps(summary, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return path","instruction":"Explain the role of `def write_summary(summary: dict[str, Any], output_path: str | Path) -> Path` in Primitive Foundry.","output":"`write_summary` is a function in `primitive_foundry.summary`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.summary.write_summary","task":"python_symbol_explanation"} {"id":"primitive_foundry.train_router.train_centroid_router::explain","input":"Module: primitive_foundry.train_router\nDomains: dataset, router\nSource path: primitive_foundry/train_router.py\n\ndef train_centroid_router(\n dataset_path: str | Path,\n output_path: str | Path,\n dimensions: int = 128,\n) -> dict[str, Any]:\n records = load_jsonl(dataset_path)\n registry = CellRegistry()\n active_ids = {cell.cell_id for cell in registry.active_cells()}\n sums: dict[str, list[float]] = {}\n counts: dict[str, int] = {}\n\n for record in records:\n vector = text_vector(record.query, dimensions)\n for cell_id in record.expected_cell_ids or [record.expected_cell_id]:\n if cell_id not in active_ids:\n continue\n sums.setdefault(cell_id, [0.0] * dimensions)\n counts[cell_id] = counts.get(cell_id, 0) + 1\n sums[cell_id] = [left + right for left, right in zip(sums[cell_id], vector)]\n\n centroids = {\n cell_id: normalize([value / counts[cell_id] for value in vector])\n for cell_id, vector in sums.items()\n }\n model = {\n \"model_type\": \"centroid-router\",\n \"created_at\": datetime.now(timezone.utc).isoformat(),\n \"training_dataset\": str(dataset_path),\n \"dimensions\": dimensions,\n \"cell_ids\": sorted(centroids),\n \"counts\": counts,\n \"centroids\": centroids,\n }\n path = Path(output_path)\n path.parent.mkdir(parents=True, exist_ok=True)\n with path.open(\"w\", encoding=\"utf-8\") as handle:\n json.dump(model, handle, indent=2, sort_keys=True)\n handle.write(\"\\n\")\n return model","instruction":"Explain the role of `def train_centroid_router(dataset_path: str | Path, output_path: str | Path, dimensions: int=128) -> dict[str, Any]` in Primitive Foundry.","output":"`train_centroid_router` is a function in `primitive_foundry.train_router`. It belongs to the dataset, router area of Primitive Foundry.","source_id":"primitive_foundry.train_router.train_centroid_router","task":"python_symbol_explanation"} {"id":"primitive_foundry.train_router.main::explain","input":"Module: primitive_foundry.train_router\nDomains: dataset, router\nSource path: primitive_foundry/train_router.py\n\ndef main() -> None:\n parser = argparse.ArgumentParser(prog=\"python -m primitive_foundry.train_router\")\n parser.add_argument(\"--dataset\", required=True)\n parser.add_argument(\"--output\", default=\"models/router_v0_1.json\")\n parser.add_argument(\"--dimensions\", type=int, default=128)\n args = parser.parse_args()\n model = train_centroid_router(args.dataset, args.output, args.dimensions)\n print(f\"Trained centroid router: {len(model['cell_ids'])} cells, output={args.output}\")","instruction":"Explain the role of `def main() -> None` in Primitive Foundry.","output":"`main` is a function in `primitive_foundry.train_router`. It belongs to the dataset, router area of Primitive Foundry.","source_id":"primitive_foundry.train_router.main","task":"python_symbol_explanation"} {"id":"primitive_foundry.v04.build_v04_splits::explain","input":"Module: primitive_foundry.v04\nDomains: dataset\nSource path: primitive_foundry/v04.py\n\ndef build_v04_splits(output_dir: str | Path = \"datasets/v0.4\") -> dict[str, Path]:\n output = Path(output_dir)\n records = generate_v03_records(240)\n train = []\n eval_records = []\n hard = []\n\n for index, record in enumerate(records):\n task = record[\"task\"]\n if task in {\"hard_negative_routing\", \"multi_cell_routing\"} or index % 10 == 0:\n hard.append(record)\n elif index % 4 == 0:\n eval_records.append(record)\n else:\n train.append(record)\n\n paths = {\n \"train\": output / \"train.jsonl\",\n \"eval\": output / \"eval.jsonl\",\n \"hard\": output / \"hard.jsonl\",\n }\n write_jsonl(train, paths[\"train\"])\n write_jsonl(eval_records, paths[\"eval\"])\n write_jsonl(hard, paths[\"hard\"])\n return paths","instruction":"Explain the role of `def build_v04_splits(output_dir: str | Path='datasets/v0.4') -> dict[str, Path]` in Primitive Foundry.","output":"`build_v04_splits` is a function in `primitive_foundry.v04`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.v04.build_v04_splits","task":"python_symbol_explanation"} {"id":"primitive_foundry.v04.write_registry_snapshots::explain","input":"Module: primitive_foundry.v04\nDomains: foundry\nSource path: primitive_foundry/v04.py\n\ndef write_registry_snapshots(output_dir: str | Path = \"registries/v0.4\") -> dict[str, Path]:\n output = Path(output_dir)\n output.mkdir(parents=True, exist_ok=True)\n pre_cells = {}\n post_cells = {}\n for cell_id, cell in SEED_CELLS.items():\n if cell_id.endswith(\".2023\"):\n pre_cells[cell_id] = replace_cell(cell, status=\"active\", trust_score=max(cell.trust_score, 0.82))\n elif cell_id.endswith(f\".{ACTIVE_YEAR}\"):\n pre_cells[cell_id] = replace_cell(cell, status=\"pending\", trust_score=cell.trust_score)\n else:\n pre_cells[cell_id] = cell\n post_cells[cell_id] = cell\n\n paths = {\n \"pre\": output / \"pre_replacement.json\",\n \"post\": output / \"post_replacement.json\",\n }\n paths[\"pre\"].write_text(json.dumps(registry_payload(pre_cells), indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n paths[\"post\"].write_text(json.dumps(registry_payload(post_cells), indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n return paths","instruction":"Explain the role of `def write_registry_snapshots(output_dir: str | Path='registries/v0.4') -> dict[str, Path]` in Primitive Foundry.","output":"`write_registry_snapshots` is a function in `primitive_foundry.v04`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.v04.write_registry_snapshots","task":"python_symbol_explanation"} {"id":"primitive_foundry.v04.replace_cell::explain","input":"Module: primitive_foundry.v04\nDomains: foundry\nSource path: primitive_foundry/v04.py\n\ndef replace_cell(cell: Cell, status: str, trust_score: float) -> Cell:\n return Cell(\n cell_id=cell.cell_id,\n domain_path=cell.domain_path,\n valid_from=cell.valid_from,\n valid_until=cell.valid_until,\n trust_score=trust_score,\n status=status,\n keywords=cell.keywords,\n answer_template=cell.answer_template,\n supersedes=cell.supersedes,\n )","instruction":"Explain the role of `def replace_cell(cell: Cell, status: str, trust_score: float) -> Cell` in Primitive Foundry.","output":"`replace_cell` is a function in `primitive_foundry.v04`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.v04.replace_cell","task":"python_symbol_explanation"} {"id":"primitive_foundry.v04.registry_payload::explain","input":"Module: primitive_foundry.v04\nDomains: foundry\nSource path: primitive_foundry/v04.py\n\ndef registry_payload(cells: dict[str, Cell]) -> dict[str, Any]:\n return {\n \"registry_version\": \"v0.4\",\n \"cells\": [asdict(cell) for cell in sorted(cells.values(), key=lambda item: item.cell_id)],\n }","instruction":"Explain the role of `def registry_payload(cells: dict[str, Cell]) -> dict[str, Any]` in Primitive Foundry.","output":"`registry_payload` is a function in `primitive_foundry.v04`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.v04.registry_payload","task":"python_symbol_explanation"} {"id":"primitive_foundry.v04.main::explain","input":"Module: primitive_foundry.v04\nDomains: dataset\nSource path: primitive_foundry/v04.py\n\ndef main() -> None:\n parser = argparse.ArgumentParser(prog=\"python -m primitive_foundry.v04\")\n parser.add_argument(\"--dataset-dir\", default=\"datasets/v0.4\")\n parser.add_argument(\"--registry-dir\", default=\"registries/v0.4\")\n args = parser.parse_args()\n dataset_paths = build_v04_splits(args.dataset_dir)\n registry_paths = write_registry_snapshots(args.registry_dir)\n print(\n \"Wrote v0.4 artifacts: \"\n + \", \".join(str(path) for path in list(dataset_paths.values()) + list(registry_paths.values()))\n )","instruction":"Explain the role of `def main() -> None` in Primitive Foundry.","output":"`main` is a function in `primitive_foundry.v04`. It belongs to the dataset area of Primitive Foundry.","source_id":"primitive_foundry.v04.main","task":"python_symbol_explanation"} {"id":"primitive_foundry.workflow.FoundryStage::explain","input":"Module: primitive_foundry.workflow\nDomains: foundry\nSource path: primitive_foundry/workflow.py\n\nclass FoundryStage:\n name: str\n purpose: str\n primary_commands: tuple[str, ...]","instruction":"Explain the role of `class FoundryStage` in Primitive Foundry.","output":"`FoundryStage` is a class in `primitive_foundry.workflow`. It belongs to the foundry area of Primitive Foundry.","source_id":"primitive_foundry.workflow.FoundryStage","task":"python_symbol_explanation"} {"id":"primitive_foundry.workflow.workflow_payload::explain","input":"Module: primitive_foundry.workflow\nDomains: release\nSource path: primitive_foundry/workflow.py\n\ndef workflow_payload() -> dict[str, object]:\n return {\n \"workflow\": \"primitive_foundry_local_private_release\",\n \"stage_order\": [stage.name for stage in WORKFLOW_STAGES],\n \"stages\": [asdict(stage) for stage in WORKFLOW_STAGES],\n }","instruction":"Explain the role of `def workflow_payload() -> dict[str, object]` in Primitive Foundry.","output":"`workflow_payload` is a function in `primitive_foundry.workflow`. It belongs to the release area of Primitive Foundry.","source_id":"primitive_foundry.workflow.workflow_payload","task":"python_symbol_explanation"}