# INITKOA CONTEXT PACK repository: Rejean-McCormick/UCKK-Moodle source_commit: 094ebff9abac8d407a5362898775eef902d2ccd1 source_mode: git working_tree_markdown: clean working_tree_selected: clean selection_mode: markdown wiki_source_commit: none wiki_working_tree_markdown: none policy_version: 2026-09-10.13 repo_files: 59 wiki_files: 0 source_files: 59 included_files: 57 excluded_files: 2 duplicate_files: 1 content_bytes: 1634483 authority_counts: {"reference":57} content_role_counts: {"knowledge":57} generated_at: 2026-09-10T13:04:10-04:00 files: 57 content_sha256: 790873b953f8ea675d45d413bf5a235b67567dc0b31d2c557409a2abb05da7be ================================================================================================ FILE INDEX ================================================================================================ 01. [reference] [knowledge] docs/00_master_execution_doctrine.md | bytes=52805 | sha256=1078b5446cfeb7c5ed955660d6388997a0c58da6a85bd5ffb701c1e3979378ab 02. [reference] [knowledge] docs/01_domain_boundaries_and_glossary.md | bytes=18895 | sha256=9815995299924c512d7fca86b24f99dde017a595a09ffde560a8216a8723efee 03. [reference] [knowledge] docs/02_distribution_architecture.md | bytes=25811 | sha256=073fa1224881542621639d180cab892126fd3927160dc0afd07938cac2a082ab 04. [reference] [knowledge] docs/03_plugin_specifications.md | bytes=66657 | sha256=873127a6e19afbae501a91a3e6ed0032bc78f970d5fc99f1b89626d90717d116 05. [reference] [knowledge] docs/04_data_model_and_storage.md | bytes=48380 | sha256=b40f484787580f345a3d49e9264ef09960f31f3d11c3f3694244d4d7f44f080e 06. [reference] [knowledge] docs/05_roles_permissions_and_security.md | bytes=48509 | sha256=c500955a9ea5f31efd001c304b902ac9cad24c4ba32e38561128d191cf130d8b 07. [reference] [knowledge] docs/06_pedagogy_courses_competencies_badges.md | bytes=30805 | sha256=6e96f9741ec513b821ff1a5e6df2cb2f9e78ea71e5ae35aef6184f22c76b7714 08. [reference] [knowledge] docs/07_challenges_and_assemblies.md | bytes=30061 | sha256=501632fbdc3d579bbb87ff180fa0c1743e83b0149a9c61f7ec185476f8e8ca90 09. [reference] [knowledge] docs/08_integrity_archives_and_privacy.md | bytes=49095 | sha256=f5a7cbe9ebd8018c0ac4335491a036e4f0f677780df5d1c639f79af60a4ffbe7 10. [reference] [knowledge] docs/09_integrations_reporting_delivery.md | bytes=67672 | sha256=9aab3e9a2bc609b99221559af7e1721294da6f716c2fca599710e51b74d96b8a 11. [reference] [knowledge] docs/10_konnaxion_smart_vote_integration_contract.md | bytes=31215 | sha256=a225c829371fe4083b7b86aecc3512319fad0326d3583d5180e9d7dd19ca163b 12. [reference] [knowledge] docs/11_cross_doc_alignment_registry.md | bytes=35293 | sha256=4ae1adcbd78f6858eacb969b536fa7baa4d489054693d680c4841656f0163350 13. [reference] [knowledge] docs/12_faculty_pages_atlas_public_contract.md | bytes=68506 | sha256=279b2698f8bd54ceebf9d343acd301503fdbb7c892f34722ff2e64c808d6e79a 14. [reference] [knowledge] docs/13_faculty_json_authoring_guide.md | bytes=57174 | sha256=771c9744ea9b92814a2cf1b1e46f8c62690fea0357bfcc8516bcd7e400fad69e 15. [reference] [knowledge] docs/14_atlas_moodle_sync_reference.md | bytes=48126 | sha256=b64a06f3578145f341859c14d489d0731fd33cb8e8f632b41ce92327c2e73fc4 16. [reference] [knowledge] docs/DOC_mediatheque_explorateur.md | bytes=23899 | sha256=66cb110d1766d9b9431fdd77d207b4ad712821fb2b44438b5b28f7d8a583483a 17. [reference] [knowledge] docs/json_preset_reference.md | bytes=39375 | sha256=99eadf867b4aaebf103b21e6af9be697f9d05272bfb97af19c3374b4a01e6ece 18. [reference] [knowledge] docs/README_import_uckkarchive_media.md | bytes=3391 | sha256=0ec3b13eb2f72907458ebf5d8a406151b855603ece3f7d58c18d9f27991c7053 19. [reference] [knowledge] docs/refactor_public_pages_contract.md | bytes=41535 | sha256=bb91672b06678ff940de388dcdfe47f8c7cb1097888fb2cf2feeef9f40579b8c 20. [reference] [knowledge] docs/TODO_refactor_explorateur_cours_public_UCKK.md | bytes=10589 | sha256=3c08e032fe23359a2ba1431cb784d020e876a175cde01951e078d6dd1d52cc42 21. [reference] [knowledge] docs/uckk-style-system-officiel.md | bytes=21737 | sha256=6fc95095c489db740b02098e76faebc39311f37d7d2858cd7cb646a38a3e7328 22. [reference] [knowledge] docs/UCKK_Moodle_Source_Runtime_Sync.md | bytes=11501 | sha256=e8e5c2df5132d027935c8a45a255851035d044ee3fbb23a3cb0f50a16b579de8 23. [reference] [knowledge] docs/UCKK_Notes_Operationnelles_Conversation_2026-06-01.md | bytes=7721 | sha256=0cc11b9afef8b019e56f4cd8249a11075d49321b2f7d9f59f59489d82a0161ea 24. [reference] [knowledge] docs/uckk_ops_console_documentation.md | bytes=16699 | sha256=4d2602cc2987d5289aa623f851ef83c23c56bb7fe9daf318d410a4691de2ffcb 25. [reference] [knowledge] docs/UCKK_Ops_Console_Runbook.md | bytes=1859 | sha256=ae080d24c52aa8227817ef621d71cf4d9c44f4e0ae842efd752494cae694cdbe 26. [reference] [knowledge] docs/UCKK_Server_Access_Runbook.md | bytes=7863 | sha256=d36b782080dc1db8185caaa27f9fa78e1467b286f04c97de28baa9c1b63bc61e 27. [reference] [knowledge] mod/uckkarchive/docs/00_index.md | bytes=21399 | sha256=e32ab9c6d969a05a05034f21886fbe7c1f4de712f534275d3ea560a768f61438 28. [reference] [knowledge] mod/uckkarchive/docs/01_architecture_decision.md | bytes=20246 | sha256=1d2f6551a10d09e9f0a34ddd723e7c2ad39a75824f971ca4b96ac3246453e1ac 29. [reference] [knowledge] mod/uckkarchive/docs/02_domain_boundaries.md | bytes=19942 | sha256=1de279e95e3bbfbfa9041030c0466e2b943fd71962638500bf5003ef24967811 30. [reference] [knowledge] mod/uckkarchive/docs/03_file_architecture.md | bytes=28778 | sha256=c21d2f7b5ec5a8f3644bf604243a72f37e89f966161ea4e41712036768ba6d97 31. [reference] [knowledge] mod/uckkarchive/docs/04_data_model.md | bytes=39262 | sha256=3f849aafbad92aa64bbe47d48b65af96e6b2a4d5093246d26947f5083fea2a67 32. [reference] [knowledge] mod/uckkarchive/docs/05_media_library.md | bytes=24331 | sha256=f38c6ed92adfed0e7868e1960db43c23597de0fdf6ec321cfe2bb5052b7bc285 33. [reference] [knowledge] mod/uckkarchive/docs/06_file_api_and_storage.md | bytes=25045 | sha256=159d24abf8eafd621f45c44d303e2766cfc735e8a1804e83488916367bab9be9 34. [reference] [knowledge] mod/uckkarchive/docs/07_permissions_and_roles.md | bytes=27231 | sha256=72049f6a72772c34e25ac13977c651dfdcd2dcfeab582ed1f83736b3af035fe6 35. [reference] [knowledge] mod/uckkarchive/docs/08_archive_workflows.md | bytes=25484 | sha256=271940dfcaff4434ac9b56a5dde3683c299e3538a63ae7f1a27e117c2bc37ac2 36. [reference] [knowledge] mod/uckkarchive/docs/09_media_workflows.md | bytes=29864 | sha256=93a97ad36d67d8f1588b13b1424107f96414c3e6749414c38d42e5f4b26d4ff8 37. [reference] [knowledge] mod/uckkarchive/docs/10_provenance_versioning_validation.md | bytes=30016 | sha256=0414b0b3970c6df3c64f6d71e342d7e9772e7bbec855dd118761c9d0586cc2c6 38. [reference] [knowledge] mod/uckkarchive/docs/11_privacy_retention_redaction.md | bytes=31290 | sha256=1f8d5a33745e40624a0392efc22105cc7b8b013593798e5c68b3052ff8e1d963 39. [reference] [knowledge] mod/uckkarchive/docs/12_backup_restore.md | bytes=31306 | sha256=534dcd9ef61100283d9eb8758f72c32e0ee295f0d425f9b780141481a751a221 40. [reference] [knowledge] mod/uckkarchive/docs/13_services_and_ajax_api.md | bytes=34090 | sha256=0dc1e4b9468278c4f9450f02e54c6ccb4f9081899dee516ea658d3c30b3fa7c9 41. [reference] [knowledge] mod/uckkarchive/docs/14_events_and_audit.md | bytes=29315 | sha256=3e6142996c6fd016f68ec169b6f6cb4631de5f678c2666606cb18f13690d7c01 42. [reference] [knowledge] mod/uckkarchive/docs/15_ui_templates_and_amd.md | bytes=26730 | sha256=da6b04ee0984a9f430e24528f2adccfd31ddb153b894cd0e4eb5e44b1279ec35 43. [reference] [knowledge] mod/uckkarchive/docs/16_integration_with_courses.md | bytes=27817 | sha256=06dded72508521f5a977fcea53dfa33dff3aa7d102a532cc9c2780a5d15438e8 44. [reference] [knowledge] mod/uckkarchive/docs/17_integration_with_challenges.md | bytes=20833 | sha256=a2405e65fe9bbcd14ad4360c6b571fa47860124c134b32261c7695f30efe160b 45. [reference] [knowledge] mod/uckkarchive/docs/18_integration_with_assemblies.md | bytes=22670 | sha256=2e77d08028b7f295724a8dbba70e4b66c8f3d1369730f618137f9a897d4a8ab8 46. [reference] [knowledge] mod/uckkarchive/docs/19_integration_with_integrity.md | bytes=22041 | sha256=a790c21cbff517f62157c16000b6aa388c126dfd000864f052edb947e039a6ac 47. [reference] [knowledge] mod/uckkarchive/docs/20_reporting_and_exports.md | bytes=28398 | sha256=918600e4310f70586ed15b2bad1c14d22baa359600fe673f9fe3422daf658b5c 48. [reference] [knowledge] mod/uckkarchive/docs/21_testing_strategy.md | bytes=24825 | sha256=85602745cf4cb2462de2f35121beaf900b0a1cf17dc14f54eb3dd5209c82feb2 49. [reference] [knowledge] mod/uckkarchive/docs/22_installation.md | bytes=27476 | sha256=0db8832e13aaafeb58ae9302fb13942613fb33af0d43305519bb726679a5dae3 50. [reference] [knowledge] mod/uckkarchive/docs/23_upgrade.md | bytes=31466 | sha256=4456607af4b2a464a9766d5ff36b173d108adefec586087547cd142c9c444695 51. [reference] [knowledge] mod/uckkarchive/docs/24_release_spec.md | bytes=28753 | sha256=b84c4e1c9480be88a982b72983e596f70da3cdf121661c4b67e54f5ef91e3f00 52. [reference] [knowledge] mod/uckkarchive/docs/26_operations_app_runtime_contract.md | bytes=16882 | sha256=80c6b5a910c1065a2714c823bf6d5ff0c377d92d836a7609933c0b586baba461 53. [reference] [knowledge] mod/uckkarchive/docs/_alignment_variables.md | bytes=26378 | sha256=1e0f66fab706b44261ac6c67c33aaddfdec69637012a622b61765aecbdb3ce63 54. [reference] [knowledge] mod/uckkarchive/README.md | bytes=12171 | sha256=ffaedd3b7d9527f91ca6c53e784441f1356d3dde810a84e8734d37eb16b4e3bd 55. [reference] [knowledge] README.md | bytes=10526 | sha256=416a91b9cd64058f4a934927ff0fd53c4c2265dfcdbf1075908d6336057296c8 56. [reference] [knowledge] release/acceptance-checklist.md | bytes=21513 | sha256=d5c06a749c93b75d26f5a4132597d7072106f354164ca6d5cd088147909dba03 57. [reference] [knowledge] UCKK_Ops_Console_Runbook.md | bytes=3232 | sha256=6d7c60aa7c28558b5c5197abbee2c1c069f9ceebe0e94f16bfd39c1442814103 ================================================================================================ EXCLUDED FILES ================================================================================================ - [reference] string_inventory/string_missing.md (repo:string_inventory/**) - [duplicate] mod/uckkarchive/docs/25_mediatheque_public_explorer.md (same content as docs/DOC_mediatheque_explorateur.md) ================================================================================================ FILE: docs/00_master_execution_doctrine.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 1078b5446cfeb7c5ed955660d6388997a0c58da6a85bd5ffb701c1e3979378ab CONTENT_BYTES: 52805 ================================================================================================ # 00 — UCKK-Moodle Master Execution Doctrine **Status:** Final implementation doctrine with standalone core and optional Konnaxion-connected alignment **Target:** Moodle 5.1 adaptation for the Univers-Cité King Klown (UCKK) **Workflow rule:** Complete final version. No stubs. No multi-phase placeholders. No "later" features inside the target scope. **Correction rule:** Generated code is not acceptable until it passes the first-pass implementation gates defined in this doctrine. Konnaxion-connected gates apply only when the connected-mode profile is enabled. ## 0. Canonical alignment variables These variables are binding across the documentation set, presets, generated code, tests, and release checks. A later file may add detail, but it must not rename, invert, or silently redefine these variables. ### 0.1 Document variables | Variable | Canonical value | Rule | | ----------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------- | | `DOC_00` | `00_master_execution_doctrine.md` | Root doctrine and correction authority. | | `DOC_01` | `01_domain_boundaries_and_glossary.md` | Domain vocabulary and forbidden/allowed wording. | | `DOC_02` | `02_distribution_architecture.md` | Plugin distribution, dependency direction, and integration layer. | | `DOC_03` | `03_plugin_specifications.md` | Plugin implementation contract. | | `DOC_04` | `04_data_model_and_storage.md` | Table ownership, enums, state machines, and storage constraints. | | `DOC_05` | `05_roles_permissions_and_security.md` | Capability and access-control registry. | | `DOC_06` | `06_pedagogy_courses_competencies_badges.md` | Courses, competencies, evidence, and badge rules. | | `DOC_07` | `07_challenges_and_assemblies.md` | Challenge, Assembly, Smart Vote, decision, and contestation workflows. | | `DOC_08` | `08_integrity_archives_and_privacy.md` | Archive, privacy, retention, redaction, and integrity safeguards. | | `DOC_09` | `09_integrations_reporting_delivery.md` | Integration contracts, reports, exports, and delivery checks. | | `DOC_10` | `10_konnaxion_smart_vote_integration_contract.md` | Optional Konnaxion-connected Smart Vote contract and acceptance gate. | | `LEGACY_DOC_10` | `10_implementation_correction_plan.md` | Deprecated. Must not be used as the active product-tree target. | ### 0.2 Source-family variables | Variable | Canonical value | Rule | | --------------------------- | ---------------------------------- | ----------------------------------------------------------------------------- | | `SOURCE_FAMILY_UCKK_CANON` | `UCKK canon` | Governs UCKK meaning, pedagogy, governance, and symbolic boundaries. | | `SOURCE_FAMILY_KONNAXION` | `Konnaxion external source family` | External source of truth for Konnaxion-side Smart Vote objects and semantics. | | `SOURCE_FAMILY_MOODLE_DOCS` | `Moodle developer documentation` | Governs Moodle 5.1 implementation mechanics. | | `EXTERNAL_SYSTEM_KONNAXION` | `Konnaxion` | Optional external system integrated through Moodle services only. | | `EXTERNAL_SIGNAL_EKOH` | `EkoH` | External ecosystem context or signal source only where explicitly mapped. | ### 0.3 Boundary variables | Variable | Canonical value | Rule | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | | `PRODUCT_SCOPE` | `UCKK-Moodle is the Moodle campus implementation of UCKK.` | It is not the whole kOA movement, kOA Digital Ecosystem, or Konnaxion platform. | | `SMART_VOTE_CANONICAL_RULE` | `Konnaxion computes Smart Vote readings. UCKK-Moodle owns Assembly decisions. Archives preserve both, with provenance and contestability.` | Must be repeated consistently in docs that mention Smart Vote. | | `SMART_VOTE_AUTHORITY` | `computed_reading_only` | Smart Vote may inform; it must not decide, award, validate, sanction, or close contestations. | | `ASSEMBLY_AUTHORITY` | `human_institutional_decision` | Final Assembly decisions belong to Moodle-side Assembly workflow and permissions. | | `ARCHIVE_AUTHORITY` | `provenance_and_contestation_memory` | Archives preserve source, snapshot, decision, minority report, and contestation trail. | | `DIRECT_WRITE_RULE` | `external_systems_never_write_moodle_source_tables` | Konnaxion must not write directly into Moodle source tables. | | `PERMISSION_RULE` | `moodle_capabilities_remain_authoritative` | External roles, labels, or identifiers never grant Moodle authority by themselves. | ### 0.4 Operating-mode variables | Variable | Canonical value | Rule | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | | `OPERATING_MODE_STANDALONE` | `standalone_core` | UCKK-Moodle installs, seeds, teaches, deliberates, archives, reports, and enforces permissions without Konnaxion. | | `OPERATING_MODE_KONNAXION_CONNECTED` | `connected_konnaxion` | Optional connected mode that adds Konnaxion bridge, EkoH/advisory signals, Smart Vote readings, and cross-module organization. | | `KONNAXION_REQUIRED_FOR_CORE` | `false` | Konnaxion must not be a hard dependency for the standalone campus. | | `SMART_VOTE_REQUIRED_FOR_CORE` | `false` | Smart Vote panels, services, mappings, snapshots, and reports must not be required for standalone workflows. | | `KONNAXION_DEFAULT_STATE` | `disabled` | The Konnaxion bridge is disabled unless an administrator explicitly configures and enables connected mode. | | `SMART_VOTE_DEFAULT_STATE` | `disabled_unless_konnaxion_connected` | Smart Vote actions are hidden or disabled unless connected mode is enabled and the user has the required capability. | | `CORE_RELEASE_GATE` | `UCKK-Moodle installs and works as a standalone campus without Konnaxion.` | Required for every release. | | `CONNECTED_KONNAXION_RELEASE_GATE` | `Konnaxion bridge and Smart Vote reading workflow work when connected mode is enabled.` | Required only for releases that claim Konnaxion-connected support. | ### 0.5 Plugin ownership variables | Variable | Canonical owner | Responsibilities | | ---------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------- | | `KONNAXION_BRIDGE_OWNER` | `local_uckk` | Connected-mode configuration, authentication settings, endpoint client, object mapping, sync logs, and shared integration services. | | `SMART_VOTE_WORKFLOW_OWNER` | `mod_uckkassembly` | Connected-mode Smart Vote reading requests, vote-target mapping, snapshots, review, contestation, and Assembly linkage. | | `ASSEMBLY_DECISION_OWNER` | `mod_uckkassembly` | Motions, deliberation, decision publication, minority report, and decision contestability. | | `SMART_VOTE_ARCHIVE_OWNER` | `mod_uckkarchive` | Archive records and file areas for Smart Vote snapshots, decisions, minutes, and provenance packages. | | `SMART_VOTE_REPORT_OWNER` | `report_uckk` | Connected-mode Smart Vote reports, institutional exports, filters, and privacy-aware visibility. | | `SMART_VOTE_INTEGRITY_OWNER` | `tool_uckkintegrity` | Integrity warnings, contested readings, correction cases, and restricted review workflows. | | `SMART_VOTE_SEED_OWNER` | `tool_uckkseed` | Idempotent connected-mode presets for capabilities, mappings, report definitions, and integration defaults. | | `SMART_VOTE_PRIVACY_OWNER` | every storing plugin | Each plugin that stores personal data owns its privacy provider, export, delete, anonymisation, and retention tests. | ### 0.6 Konnaxion object variables | Variable | Canonical value | Moodle-side use | | -------------------------------------- | -------------------- | ---------------------------------------------------------------------------- | | `KONNAXION_OBJECT_VOTE` | `Vote` | External vote object mapped to a Moodle-side vote target or reading source. | | `KONNAXION_OBJECT_VOTE_MODALITY` | `VoteModality` | External voting modality/method mapped to a Moodle-side reading method. | | `KONNAXION_OBJECT_VOTE_RESULT` | `VoteResult` | External result mapped into a Moodle-side Smart Vote reading snapshot. | | `KONNAXION_OBJECT_INTEGRATION_MAPPING` | `IntegrationMapping` | External mapping object mirrored by Moodle-side mapping tables. | | `KONNAXION_EXTERNAL_ID_FIELD` | `externalid` | Stores the Konnaxion identifier; never stores secrets. | | `KONNAXION_EXTERNAL_TYPE_FIELD` | `externaltype` | Stores the Konnaxion object type. | | `KONNAXION_SOURCE_VERSION_FIELD` | `sourceversion` | Stores the external source version, revision, or timestamp where available. | | `KONNAXION_SYNC_STATUS_FIELD` | `syncstatus` | Stores Moodle-side sync state using the enum below. | | `KONNAXION_PROVENANCE_HASH_FIELD` | `provenancehash` | Stores integrity hash for imported snapshots or mapped records where needed. | ### 0.7 Moodle-side Konnaxion table variables | Variable | Canonical table | Owner | Purpose | | ------------------------------- | ------------------------------ | ------------------ | ---------------------------------------------------------------------------------------------- | | `TABLE_KONNAXION_USER_MAP` | `local_uckk_kx_user_map` | `local_uckk` | Maps Moodle users to Konnaxion identities without exposing unnecessary external personal data. | | `TABLE_KONNAXION_OBJECT_MAP` | `local_uckk_kx_object_map` | `local_uckk` | Maps Moodle objects to Konnaxion objects. | | `TABLE_KONNAXION_SYNC_LOG` | `local_uckk_kx_sync_log` | `local_uckk` | Logs sync attempts, failures, retries, endpoint responses, and idempotency keys. | | `TABLE_SMART_VOTE_TARGET_MAP` | `uckkassembly_kx_vote_target` | `mod_uckkassembly` | Maps Assembly motions, decisions, or deliberation objects to Konnaxion vote targets. | | `TABLE_SMART_VOTE_SNAPSHOT` | `uckkassembly_sv_snapshot` | `mod_uckkassembly` | Stores Moodle-side immutable Smart Vote reading snapshots. | | `TABLE_SMART_VOTE_RESULT_AUDIT` | `uckkassembly_sv_result_audit` | `mod_uckkassembly` | Stores review, correction, contestation, and supersession trail for Smart Vote results. | The abbreviation `kx` is allowed only in table and internal variable names. User-facing documentation and UI must use `Konnaxion`. These tables are connected-mode tables; they are not required to contain records, expose UI, or run sync tasks in standalone mode. ### 0.8 Smart Vote reading variables | Variable | Canonical field/key | Rule | | ------------------------ | ------------------------------ | ---------------------------------------------------------------------------- | | `SV_RAW_DATA` | `raw_data` | Imported or referenced source facts before interpretation. | | `SV_READING_METHOD` | `reading_method` | The declared method, modality, weighting, or algorithmic reading rule. | | `SV_COMPUTED_READING` | `computed_reading` | The non-sovereign Smart Vote output. | | `SV_EXPERTISE_WEIGHT` | `expertise_weight` | Any weighted-reading factor; personal or sensitive where linkable to a user. | | `SV_HUMAN_DECISION` | `human_institutional_decision` | Moodle-side Assembly decision; must not be overwritten by Smart Vote. | | `SV_MINORITY_REPORT` | `minority_report` | Documented minority position or dissenting signal. | | `SV_INTEGRITY_WARNING` | `integrity_warning` | Warning or flag that may open integrity review but is not itself a sanction. | | `SV_CONTESTATION_STATUS` | `contestation_status` | Contestation state for the snapshot or decision linkage. | | `SV_ARCHIVE_ITEM_ID` | `archiveitemid` | Link to preserved archive item when archived. | ### 0.9 Status and state variables | Variable | Allowed values | Owner | | --------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------ | | `KONNAXION_SYNC_STATUS_ENUM` | `queued`, `running`, `succeeded`, `failed`, `retry_waiting`, `skipped`, `disabled` | `local_uckk` | | `KONNAXION_MAPPING_STATUS_ENUM` | `draft`, `active`, `suspended`, `superseded`, `archived`, `invalidated` | `local_uckk` | | `SMART_VOTE_TARGET_STATUS_ENUM` | `draft`, `mapped`, `active`, `closed`, `archived`, `contested` | `mod_uckkassembly` | | `SMART_VOTE_SNAPSHOT_STATUS_ENUM` | `imported`, `under_review`, `accepted_as_reading`, `contested`, `superseded`, `archived`, `invalidated` | `mod_uckkassembly` | | `SMART_VOTE_AUDIT_STATUS_ENUM` | `recorded`, `reviewed`, `corrected`, `contested`, `resolved` | `mod_uckkassembly` | These values must be copied into `DOC_04`, `DOC_07`, `DOC_09`, `DOC_10`, `presets/state_machines.json`, PHPUnit state-machine tests, Behat workflow tests, and privacy/export tests where applicable. Konnaxion and Smart Vote state machines are mandatory only for the connected-mode profile. ### 0.10 Capability variables | Variable | Canonical capability | Owner | | ----------------------------- | ----------------------------------- | ------------------ | | `CAP_MANAGE_KONNAXION` | `local/uckk:managekonnaxion` | `local_uckk` | | `CAP_MAP_KONNAXION_OBJECTS` | `local/uckk:mapkonnaxionobjects` | `local_uckk` | | `CAP_VIEW_KONNAXION_LOGS` | `local/uckk:viewkonnaxionlogs` | `local_uckk` | | `CAP_REQUEST_SMART_VOTE` | `mod/uckkassembly:requestsmartvote` | `mod_uckkassembly` | | `CAP_VIEW_SMART_VOTE` | `mod/uckkassembly:viewsmartvote` | `mod_uckkassembly` | | `CAP_REVIEW_SMART_VOTE` | `mod/uckkassembly:reviewsmartvote` | `mod_uckkassembly` | | `CAP_CONTEST_SMART_VOTE` | `mod/uckkassembly:contestsmartvote` | `mod_uckkassembly` | | `CAP_ARCHIVE_SMART_VOTE` | `mod/uckkarchive:archivesmartvote` | `mod_uckkarchive` | | `CAP_VIEW_SMART_VOTE_REPORTS` | `report/uckk:viewsmartvotereports` | `report_uckk` | Every capability above must appear in `db/access.php`, `DOC_05`, `presets/capabilities.json`, PHPUnit access tests, and Behat role-visibility tests before the connected-mode Konnaxion pass is complete. Standalone core workflows must not require these capabilities. ### 0.11 Service and event variables | Variable | Canonical name | Owner | | ------------------------------------- | ------------------------------------------------------ | ------------------ | | `SERVICE_CREATE_KONNAXION_MAPPING` | `local_uckk_create_konnaxion_mapping` | `local_uckk` | | `SERVICE_GET_KONNAXION_MAPPING` | `local_uckk_get_konnaxion_mapping` | `local_uckk` | | `SERVICE_SYNC_KONNAXION` | `local_uckk_sync_konnaxion` | `local_uckk` | | `SERVICE_REQUEST_SMART_VOTE_READING` | `mod_uckkassembly_request_smart_vote_reading` | `mod_uckkassembly` | | `SERVICE_IMPORT_SMART_VOTE_SNAPSHOT` | `mod_uckkassembly_import_smart_vote_snapshot` | `mod_uckkassembly` | | `SERVICE_CONTEST_SMART_VOTE_SNAPSHOT` | `mod_uckkassembly_contest_smart_vote_snapshot` | `mod_uckkassembly` | | `SERVICE_GET_SMART_VOTE_REPORT` | `report_uckk_get_smart_vote_report` | `report_uckk` | | `EVENT_KONNAXION_MAPPING_CREATED` | `local_uckk\event\konnaxion_mapping_created` | `local_uckk` | | `EVENT_KONNAXION_SYNC_COMPLETED` | `local_uckk\event\konnaxion_sync_completed` | `local_uckk` | | `EVENT_SMART_VOTE_READING_REQUESTED` | `mod_uckkassembly\event\smart_vote_reading_requested` | `mod_uckkassembly` | | `EVENT_SMART_VOTE_SNAPSHOT_IMPORTED` | `mod_uckkassembly\event\smart_vote_snapshot_imported` | `mod_uckkassembly` | | `EVENT_SMART_VOTE_SNAPSHOT_CONTESTED` | `mod_uckkassembly\event\smart_vote_snapshot_contested` | `mod_uckkassembly` | | `EVENT_SMART_VOTE_SNAPSHOT_ARCHIVED` | `mod_uckkassembly\event\smart_vote_snapshot_archived` | `mod_uckkassembly` | Every connected-mode service must have a `db/services.php` declaration, `classes/external/*` implementation, parameter validation, return validation, capability checks, privacy notes, PHPUnit coverage, and failure-path tests. Every connected-mode event must have a matching `classes/event/*` implementation and must avoid leaking private Smart Vote or Konnaxion data in descriptions. Standalone mode must remain functional when these services are disabled by configuration. ### 0.12 Preset registry variables | Variable | Canonical preset | Required by | | --------------------------- | --------------------------------- | ------------------------------------------------------------------------- | | `PRESET_CAPABILITIES` | `presets/capabilities.json` | Roles, capabilities, tests, seed tool. | | `PRESET_STATE_MACHINES` | `presets/state_machines.json` | Workflow statuses and transitions. | | `PRESET_EVENTS` | `presets/events.json` | Event-class registry and tests. | | `PRESET_KONNAXION_MAPPINGS` | `presets/konnaxion_mappings.json` | Connected-mode Konnaxion object map defaults and validation fixtures. | | `PRESET_PRIVACY_RETENTION` | `presets/privacy_retention.json` | Privacy, export, deletion, anonymisation, redaction, and retention tests. | | `PRESET_EXPORTS` | `presets/exports.json` | Report/export definitions and acceptance evidence. | ## 1. Purpose This documentation set defines the coherent final adaptation of Moodle into the operational campus of UCKK. The goal is not to decorate Moodle and not to fork Moodle unnecessarily. The goal is to deliver a complete, installable, governed Moodle distribution that expresses UCKK through Moodle-native extension points, complete plugins, seed data, roles, capabilities, activities, reports, archives, AI governance, optional Konnaxion-connected Smart Vote integration, and institutional safeguards. This doctrine is also the correction contract for implementation passes. When generated code contradicts this doctrine, the doctrine wins and the code must be corrected. When connected-mode Konnaxion integration code contradicts the Smart Vote boundary in this doctrine, the boundary wins on the Moodle side and the implementation must be corrected. ## 2. Governing decision UCKK-Moodle is the **campus implementation** of the Univers-Cité King Klown. It is: * a Moodle-based learning and governance environment; * a complete pedagogical distribution; * a set of coordinated Moodle plugins; * an institutional seed package; * a delivery contract for implementation teams; * a correction standard for generated or assisted code; * a governed optional integration surface for external kOA systems such as Konnaxion when they assist UCKK workflows without owning Moodle records. It is not: * the whole kOA movement; * the whole kOA Digital Ecosystem; * the Konnaxion platform; * a Smart Vote authority that replaces Assemblées, archive provenance, or institutional decision records; * a generic LMS skin; * a symbolic website only; * a fork of Moodle core unless a core change is absolutely unavoidable; * an experimental skeleton containing stubs; * a collection of files that only looks complete by name. ## 3. Canonical boundary The implementation must preserve this hierarchy: ```text kOA = movement UCKK = school / learning city kOA Digital Ecosystem = operational digital infrastructure King Klown = narrative and mobilizing figure Inquisiteur = ethical and methodological guardrail Assemblées = collective legitimacy Archives = memory Konnaxion = optional external Smart Vote and participation-reading source family EkoH = external ecosystem context or signal source where explicitly mapped Smart Vote = computed reading, never final institutional decision ``` Every UI label, plugin responsibility, data model, and permission must preserve the distinction. The Konnaxion/Smart Vote boundary is canonical: ```text Konnaxion computes Smart Vote readings. UCKK-Moodle owns Assembly decisions. Archives preserve both, with provenance and contestability. ``` In connected mode, Smart Vote may inform a deliberation, provide a computed reading, expose minority signals, and support reporting. Smart Vote must not publish a final Assembly decision, award UCKK recognition, validate evidence, close a contestation, or bypass Moodle permissions. ## 4. Final product definition The final version is delivered as: ```text uckk-moodle/ ├── docs/ │ ├── 00_master_execution_doctrine.md │ ├── 01_domain_boundaries_and_glossary.md │ ├── 02_distribution_architecture.md │ ├── 03_plugin_specifications.md │ ├── 04_data_model_and_storage.md │ ├── 05_roles_permissions_and_security.md │ ├── 06_pedagogy_courses_competencies_badges.md │ ├── 07_challenges_and_assemblies.md │ ├── 08_integrity_archives_and_privacy.md │ ├── 09_integrations_reporting_delivery.md │ └── 10_konnaxion_smart_vote_integration_contract.md │ ├── plugins/ │ ├── theme/uckk │ ├── course/format/uckk │ ├── local/uckk │ ├── blocks/uckk_dashboard │ ├── mod/uckkchallenge │ ├── mod/uckkassembly │ ├── mod/uckkarchive │ ├── admin/tool/uckkseed │ ├── admin/tool/uckkintegrity │ ├── report/uckk │ └── ai/provider/uckk │ ├── presets/ │ ├── categories.json │ ├── courses.json │ ├── cohorts.json │ ├── roles.json │ ├── capabilities.json │ ├── competencies.json │ ├── badges.json │ ├── reports.json │ ├── navigation.json │ ├── state_machines.json │ ├── events.json │ ├── konnaxion_mappings.json │ ├── privacy_retention.json │ └── exports.json │ ├── tests/ │ ├── phpunit/ │ ├── behat/ │ └── fixtures/ │ └── release/ ├── installation.md ├── upgrade.md ├── rollback.md └── acceptance-checklist.md ``` The `plugins/` path is the distribution packaging path. The same plugins must be installable at their Moodle-native locations, for example `local/uckk`, `mod/uckkarchive`, `admin/tool/uckkseed`, `course/format/uckk`, `blocks/uckk_dashboard`, `theme/uckk`, `report/uckk`, and `ai/provider/uckk`. `presets/konnaxion_mappings.json` is a connected-mode preset. Its absence, emptiness, or disabled state must not block standalone installation or seed execution unless the release explicitly claims connected-mode support. The old `10_implementation_correction_plan.md` slot is replaced by `10_konnaxion_smart_vote_integration_contract.md`. `DOC_10` is the optional connected-mode contract for Konnaxion Smart Vote. It must not be used to make Konnaxion a hard dependency of the standalone campus. ## 5. No-stub implementation rule Every plugin in scope must be production-complete at delivery. A plugin is not complete unless it contains: ```text version.php db/install.xml when storing data db/upgrade.php when data schema may evolve db/access.php for capabilities db/services.php when exposing AJAX, external, mobile, or web-service functions db/tasks.php when scheduled or asynchronous work exists lang/en/.php lang/fr/.php classes/ classes/privacy/provider.php when personal data is stored classes/external/* for every db/services.php function classes/form/* for every Moodle form referenced by a page or workflow classes/event/* for every declared or triggered event classes/output/* for renderables, exporters, tables, or template view models classes/task/* for every scheduled task classes/service/* or classes/local/* for integration, registry, Konnaxion bridge, and Smart Vote business services when connected mode is enabled settings.php when configurable lib.php when Moodle plugintype requires it locallib.php only for procedural helper functions that are safe outside upgrade/install context amd/src/*.js when client-side behaviour is required templates/*.mustache when server-rendered UI is required tests/phpunit tests/behat README.md ``` A plugin may have intentionally disabled features only if the disabled behavior is a documented configuration option, not an unfinished stub. A page, service, task, event, AMD module, template, capability, install step, upgrade step, or test that references a missing class is a defect, not a placeholder. ## 6. First-pass implementation correction gates Before any Moodle installation attempt, generated code must pass these first-pass gates. ### Gate 1 — Filetype correctness Every file must contain code appropriate to its extension and Moodle location: ```text .php files must start with theme_uckk course/format/uckk => format_uckk local/uckk => local_uckk blocks/uckk_dashboard => block_uckk_dashboard mod/uckkchallenge => mod_uckkchallenge mod/uckkassembly => mod_uckkassembly mod/uckkarchive => mod_uckkarchive admin/tool/uckkseed => tool_uckkseed admin/tool/uckkintegrity => tool_uckkintegrity report/uckk => report_uckk ai/provider/uckk => aiprovider_uckk ``` The `@package` value, `$plugin->component`, language component names, capability prefixes, service component names, event namespaces, AMD module names, template names, and test namespaces must agree with the component. ### Gate 3 — Class-layer completeness The `classes/` layer is mandatory for any plugin that declares or uses namespaced services, forms, events, outputs, scheduled tasks, privacy providers, or business services. Procedural `lib.php` and `locallib.php` files may expose Moodle callbacks and stable helpers. They must not replace the class layer for: ```text external service implementations forms renderables/exporters/view models events scheduled tasks privacy providers integrity decisions archive validation engines assembly decision engines challenge submission engines Konnaxion bridge services Smart Vote reading import, snapshot, reporting, and contestation services AI processing providers ``` ### Gate 4 — Access and context correctness Every user-facing page and every service endpoint must define: ```text required login state Moodle context required capability parameter validation sesskey requirement for state changes redirect or error behavior for unauthorized access audit/event behavior when state changes external-system boundary when the action uses Konnaxion or another integration ``` When connected-mode support is claimed, Konnaxion-facing services must additionally define authentication, endpoint ownership, request validation, timeout behavior, failure behavior, retry/idempotency policy, sync direction, provenance, audit event emission, and privacy impact. No UCKK-specific role may be implemented as a hidden global administrator. The Inquisiteur, Archiviste, Mentor, Bâtisseur, and assembly roles must be capability-limited and auditable. ### Gate 5 — Data and upgrade correctness Every table must have: ```text owning plugin install.xml definition upgrade path when schema may evolve backup/restore coverage when activity data is portable privacy export/delete behavior when personal data exists test coverage for create/read/update/delete and integrity constraints ``` When connected-mode support is claimed, Konnaxion mapping, sync, Smart Vote snapshot, external result audit, and vote-target mapping tables must be owned by exactly one Moodle plugin and must never allow Konnaxion to write directly into Moodle source tables. Files in `db/` must remain self-contained. They must not include plugin libraries, render UI, call workflow logic, or rely on classes that may not be available during install or upgrade. ### Gate 6 — Privacy correctness Every plugin that stores or exposes personal data must implement `classes/privacy/provider.php`. Privacy coverage must include: ```text user profile extensions challenge submissions and evidence assembly participation, votes, minutes, and decisions archive items, provenance, proof files, and validation states integrity cases, appeals, decisions, and audit notes seed logs that identify users reports that expose user-related data AI prompts, outputs, summaries, logs, or moderation traces when retained connected-mode Konnaxion user mappings, object mappings, vote-target mappings, sync logs, result snapshots, reading methods, external identifiers, expertise weights, and Smart Vote audit records ``` ### Gate 7 — Test and build correctness A generated pass is not acceptable until the following can run cleanly in a disposable Moodle development installation: ```text php -l on all PHP files JSON validation on all presets XML validation on all install.xml files Moodle plugin discovery admin/cli/upgrade.php --non-interactive Moodle cache purge Moodle AMD build through Grunt PHPUnit for each plugin Behat for each major workflow privacy API tests for plugins with personal data backup/restore tests for activity modules seed idempotency tests connected-mode Konnaxion connector tests with mocked responses when connected-mode support is claimed connected-mode Smart Vote reading snapshot tests when connected-mode support is claimed connected-mode Konnaxion timeout, failure, retry, disabled-state, and idempotency tests when connected-mode support is claimed connected-mode report/export tests for Konnaxion-derived data when connected-mode support is claimed ``` ### Gate 8 — Canonical alignment variable correctness The canonical alignment pass is not complete until every core variable in section 0 is resolved consistently across documentation, presets, code, tests, and release artifacts. Connected-mode Konnaxion variables must also be resolved for any release that claims Konnaxion Smart Vote support. Blocking defects include: ```text an active product tree still pointing to 10_implementation_correction_plan.md using Smart Vote as a final decision authority renaming connected-mode Konnaxion tables, services, events, capabilities, or status enums outside the registry using Konnaxion, EkoH, Smart Vote, Assembly decision, imported reading, result snapshot, and minority report interchangeably storing connected-mode Konnaxion personal data without privacy-provider coverage storing imported readings without raw data, reading method, computed reading, decision linkage, provenance, and contestation status allowing an external identifier or symbolic role to grant Moodle capability missing connected-mode tests for timeout, failure, retry, disabled state, idempotency, privacy export, and contestation paths when connected-mode support is claimed ``` Every generated implementation pass must include a variable-resolution checklist proving that: ```text DOC_00 through DOC_10 use the same document names connected-mode Konnaxion object variables map to Moodle-side table variables when connected-mode support is claimed all core capability variables exist in db/access.php and presets/capabilities.json; connected-mode capabilities exist when connected-mode support is claimed all enabled service variables exist in db/services.php and classes/external all enabled event variables exist in classes/event and presets/events.json all core status variables exist in DOC_04, DOC_07, DOC_09, and presets/state_machines.json; connected-mode status variables also exist in DOC_10 when connected-mode support is claimed all privacy/retention variables exist in DOC_08 and presets/privacy_retention.json all core report/export variables exist in DOC_09, report_uckk, and presets/exports.json; connected-mode report/export variables exist when connected-mode support is claimed ``` ## 7. Core strategy Moodle core remains untouched unless all of the following are true: 1. no plugin type can implement the requirement; 2. no theme override can implement the UI requirement safely; 3. no course format override can implement the course behavior; 4. no admin tool, local plugin, report source, or web service can implement the cross-cutting behavior; 5. the change has a written justification and a rollback strategy. A failing plugin implementation is not evidence that Moodle core must be changed. Core changes are justified only after plugin, theme, course format, local plugin, admin tool, report, block, web service, and AI provider extension points have been exhausted. External integrations follow the same rule. Konnaxion, when enabled, must be integrated through Moodle plugins, settings, services, scheduled tasks, events, reports, and privacy providers. Konnaxion must not require direct database writes into Moodle source tables, hidden administrator privileges, Moodle core patches, or unlogged bypasses of Assembly, Archive, Integrity, or capability workflows. Disabling Konnaxion must not disable standalone UCKK-Moodle workflows. ## 8. Source anchors The implementation is governed by three source families: ### UCKK canon * `UCKK_Canon/00_index.md` * `UCKK_Canon/01_glossaire.md` * `UCKK_Canon/02_architecture-generale-kOA-UCKK-digital-ecosystem.md` * `UCKK_Canon/20_UCKK-document-fondateur.md` * `UCKK_Canon/22_UCKK-gouvernance-assemblees-inquisiteur.md` * `UCKK_Canon/23_UCKK-defis-theatre-public.md` * `UCKK_Canon/30_UCKK-catalogue-academique.md` * `UCKK_Canon/31_UCKK-tronc-commun.md` * `UCKK_Canon/42_UCKK-liste-et-fiches-de-cours.md` * `UCKK_Canon/cours/*.md` ### Konnaxion external source family The Konnaxion reference file is an external source of truth for Konnaxion-side Smart Vote concepts. It must not be rewritten as part of UCKK-Moodle unless a documented contradiction is found in the Konnaxion source itself. The connected-mode Moodle implementation must map, at minimum, the Konnaxion objects: ```text Vote VoteModality VoteResult IntegrationMapping ``` In connected mode, Konnaxion source data may be imported, snapshotted, reported, contested, and archived inside Moodle only through documented Moodle-side services and tables. The Konnaxion source remains external; UCKK-Moodle owns its local mappings, Assembly decisions, reports, privacy handling, and archive records. ### Moodle developer documentation * `versioned_docs/version-5.1/apis.md` * `versioned_docs/version-5.1/apis/plugintypes/index.md` * `versioned_docs/version-5.1/apis/plugintypes/local/index.mdx` * `versioned_docs/version-5.1/apis/plugintypes/format/index.md` * `versioned_docs/version-5.1/apis/plugintypes/mod/index.mdx` * `versioned_docs/version-5.1/apis/plugintypes/theme/index.md` * `versioned_docs/version-5.1/apis/plugintypes/blocks/index.md` * `versioned_docs/version-5.1/apis/subsystems/access.md` * `versioned_docs/version-5.1/apis/subsystems/privacy/index.md` * `versioned_docs/version-5.1/apis/core/reportbuilder/index.md` * `versioned_docs/version-5.1/apis/subsystems/ai/index.md` * `versioned_docs/version-5.1/apis/javascript/index.md` * `versioned_docs/version-5.1/apis/subsystems/external/index.md` * `versioned_docs/version-5.1/apis/subsystems/files/index.md` * `versioned_docs/version-5.1/apis/subsystems/backup/index.md` * `versioned_docs/version-5.1/apis/subsystems/events/index.md` * `versioned_docs/version-5.1/apis/subsystems/tasks.md` * `versioned_docs/version-5.1/apis/subsystems/output/index.md` * `versioned_docs/version-5.1/apis/tools/phpunit/index.md` * `versioned_docs/version-5.1/apis/tools/behat/index.md` ### Canonical registries The documentation set must maintain these registries before generated implementation code is considered aligned: | Registry | Canonical location | Purpose | | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | | Capability registry | `05_roles_permissions_and_security.md` and `presets/capabilities.json` | Every capability declared in code, docs, tests, and seed data. | | State-machine registry | `04_data_model_and_storage.md`, `07_challenges_and_assemblies.md`, and `presets/state_machines.json` | Allowed workflow states and transitions. | | Event-class registry | `02_distribution_architecture.md`, `03_plugin_specifications.md`, `07_challenges_and_assemblies.md`, `09_integrations_reporting_delivery.md`, and `presets/events.json` | Every emitted or observed Moodle event. | | Konnaxion mapping registry | `04_data_model_and_storage.md`, `09_integrations_reporting_delivery.md`, `10_konnaxion_smart_vote_integration_contract.md`, and `presets/konnaxion_mappings.json` | Connected-mode external identifiers, Moodle-side objects, vote targets, snapshots, and sync status. | | Seed preset path registry | This doctrine, `09_integrations_reporting_delivery.md`, and `tool_uckkseed` tests | All required preset files and idempotent seed behavior. | | Privacy/retention registry | `08_integrity_archives_and_privacy.md` and `presets/privacy_retention.json` | Export, deletion, anonymisation, redaction, archive retention, and contestation retention. | | Report/export registry | `09_integrations_reporting_delivery.md`, `report_uckk`, and `presets/exports.json` | Institutional reports, Smart Vote reports, archive exports, and acceptance evidence. | No implementation pass may treat these registries as optional prose. Code, seed data, tests, and release acceptance must agree with the core registries for every release, and with the Konnaxion mapping registry for every release that claims connected-mode support. ## 9. Completion standard UCKK-Moodle has two release gates: standalone core and optional Konnaxion-connected mode. The standalone core gate is mandatory for every release. The Konnaxion-connected gate is mandatory only for releases that claim Konnaxion Smart Vote support. ### 9.1 Core standalone completion The standalone adaptation is complete only when a clean Moodle installation can be turned into UCKK-Moodle by installing the package and running the seed tool, producing: * UCKK categories; * tronc commun courses; * internal programs; * roles and capabilities; * cohorts; * competencies; * badges; * dashboards; * challenge activity; * assembly activity; * archive activity; * integrity system; * reports; * AI provider configuration that can be enabled or disabled safely; * canonical core alignment variables resolved across docs, presets, services, events, tables, capabilities, privacy, reports, and tests; * privacy providers; * tests; * documentation; * acceptance evidence. Standalone completion must not require Konnaxion credentials, Konnaxion mappings, Smart Vote snapshots, Smart Vote reports, external vote portals, Konnaxion sync tasks, or Konnaxion API availability. ### 9.2 Optional Konnaxion-connected completion The connected-mode profile is complete only when the standalone gate passes and the enabled Konnaxion profile additionally provides: * Konnaxion integration configuration; * Konnaxion bridge enable/disable controls; * Konnaxion mapping registry; * Konnaxion health check without secret exposure; * Konnaxion timeout, failure, retry, idempotency, and disabled-state behavior; * Smart Vote target mapping; * Smart Vote reading requests; * Smart Vote reading snapshots; * Smart Vote review, contestation, supersession, and archive linkage; * Smart Vote reports and exports; * connected-mode privacy, retention, redaction, provenance, and audit coverage; * connected-mode PHPUnit, Behat, and failure-path acceptance evidence. Completion requires both functional behavior and implementation hygiene. A feature that appears in the UI but fails install checks, privacy checks, upgrade checks, build checks, capability checks, or test checks is incomplete. A connected-mode feature that is disabled must fail closed without breaking standalone workflows. ## 10. Non-negotiable final checks The final implementation must pass the core checks for every release. Connected-mode checks apply only when the release claims Konnaxion Smart Vote support. ### 10.1 Core standalone checks ```text [ ] Moodle core remains clean or every core change is justified. [ ] Every plugin installs without warnings with Konnaxion disabled. [ ] Every plugin has version metadata and dependency declarations. [ ] No plugin declares Konnaxion as a hard dependency for standalone mode. [ ] Every plugin component name matches its Moodle-native path. [ ] Every PHP source file parses with php -l. [ ] Every JavaScript AMD source file contains JavaScript only. [ ] Every PHP controller file contains PHP only and starts correctly. [ ] No Markdown fences or implementation notes remain inside executable source files. [ ] Every core table has install and upgrade support. [ ] Every db/ file is self-contained and safe during install/upgrade. [ ] Every enabled db/services.php declaration has a matching classes/external implementation. [ ] Every referenced form class exists under classes/form. [ ] Every triggered or declared event class exists under classes/event. [ ] Every scheduled task declaration has a matching classes/task implementation or is disabled by configuration. [ ] Every renderable/exporter/view model exists under classes/output or another appropriate class namespace. [ ] Every personal data store has a privacy provider. [ ] Every privacy provider is tested for export, deletion, and metadata coverage. [ ] Every capability is explicit and context-aware. [ ] Every state-changing page or service validates sesskey and permissions. [ ] Every major standalone workflow has Behat coverage. [ ] Every data service has PHPUnit coverage. [ ] Every activity module has backup/restore coverage. [ ] Moodle AMD build passes. [ ] Core preset JSON validates. [ ] The seed tool can create a full standalone UCKK campus. [ ] The seed tool can be re-run idempotently. [ ] The UCKK / kOA / kOA Digital Ecosystem / King Klown / Konnaxion distinction remains visible. [ ] Badges and competencies are linked to evidence. [ ] Challenges and assemblies are auditable without Smart Vote. [ ] Assembly decisions work without Konnaxion or Smart Vote. [ ] Archives preserve provenance without requiring Smart Vote snapshots. [ ] The Inquisiteur cannot become an unrestricted super-admin by design. [ ] AI outputs are never final authority. [ ] Canonical core alignment variables from section 0 are resolved consistently across docs, presets, code, tests, and release artifacts. [ ] `DOC_10` is `10_konnaxion_smart_vote_integration_contract.md` and is treated as optional connected-mode contract. ``` ### 10.2 Optional Konnaxion-connected checks ```text [ ] Konnaxion bridge is disabled safely by default. [ ] Konnaxion can be enabled and disabled from Moodle administration settings. [ ] Disabling Konnaxion hides or disables Smart Vote actions without breaking Assemblies. [ ] Konnaxion table names match the canonical `TABLE_*` variables. [ ] Konnaxion capabilities match the canonical `CAP_*` variables. [ ] Konnaxion services and events match the canonical `SERVICE_*` and `EVENT_*` variables. [ ] Smart Vote status values match the canonical `*_STATUS_ENUM` variables. [ ] Konnaxion is declared as an external source family and never mistaken for Moodle ownership. [ ] Konnaxion never writes directly into Moodle source tables. [ ] Konnaxion mappings preserve external identifiers without exposing secrets or unnecessary personal data. [ ] Smart Vote readings distinguish raw data, reading method, computed reading, human/institutional decision, minority report, and integrity warning. [ ] Smart Vote readings cannot publish final Assembly decisions. [ ] UCKK-Moodle Assembly decisions remain human/institutional, permission-checked, archived, and contestable. [ ] Konnaxion timeout, failure, retry, disabled-state, and sync behavior is documented and tested. [ ] Konnaxion-derived reports and exports preserve provenance and privacy controls. [ ] Konnaxion outage fails safely and never fabricates or silently accepts results. ``` ## 11. First-pass correction priority When an implementation pass produces errors, corrections must happen in this order: ```text 1. Filetype correctness errors that prevent parsing or building. 2. Canonical alignment variable conflicts that would make generated files disagree. 3. Moodle component-name and plugin-discovery errors. 4. Missing classes referenced by services, pages, events, forms, tasks, outputs, or tests. 5. Database install/upgrade defects. 6. Connected-mode Konnaxion mapping, service-contract, source-table direct-write, disabled-state, and Smart Vote sovereignty defects. 7. Capability, context, sesskey, and access-control defects. 8. Privacy-provider defects. 9. Backup/restore defects. 10. PHPUnit failures. 11. Behat failures. 12. UI polish, language improvements, and non-blocking refinements. ``` A Moodle browser installation attempt must not be used as the first diagnostic step. Static checks and disposable CLI install checks come first. ## 12. Primary formula > UCKK-Moodle is the standalone Moodle campus of the Univers-Cité King Klown: pedagogical like Moodle, symbolic like UCKK, governable like kOA, traceable like an archive, and contestable like a healthy institution. > > Konnaxion is an optional connected-mode integration. When connected, Konnaxion may compute Smart Vote readings, but UCKK-Moodle Assemblées decide, and Archives preserve both. ================================================================================================ FILE: docs/01_domain_boundaries_and_glossary.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 9815995299924c512d7fca86b24f99dde017a595a09ffde560a8216a8723efee CONTENT_BYTES: 18895 ================================================================================================ # 01 — Domain Boundaries and Glossary **Status:** Final domain specification, standalone/Konnaxion-aligned **Purpose:** Prevent conceptual confusion during design, development, UI writing, seeding, permissions, reporting, documentation, connected integrations, and implementation review. ## 1. Boundary model UCKK-Moodle must preserve a strict domain separation: | Domain | Meaning | Moodle implementation | |---|---|---| | kOA | Movement, culture, method, social vision | Referenced, taught, integrated through selected APIs | | UCKK | School / learning city | Main campus implemented in Moodle | | UCKK-Moodle | Moodle campus implementation of UCKK | Self-standing Moodle distribution; must install and operate without Konnaxion | | kOA Digital Ecosystem | Operational digital infrastructure | External or future integration target, not collapsed into Moodle | | Konnaxion | External collective-intelligence platform | Optional connected-mode integration; provides Smart Vote/EkoH readings and better cross-module organization when enabled | | EkoH | External expertise, ethics, reputation, or weighting signal from Konnaxion | Advisory signal only where explicitly mapped; never Moodle authority by itself | | Smart Vote | Konnaxion weighted reading system | Optional Assembly reading in connected mode; never final Moodle decision | | King Klown | Narrative figure | Branding, challenges, symbolic pedagogy | | Inquisiteur | Ethical and methodological guardrail | Integrity system and restricted capabilities | | Assemblées | Collective legitimacy | Structured assembly activity and decision records | | Archives | Memory | Archive activity, evidence records, provenance, reports | Core boundary invariant: ```text UCKK-Moodle is self-standing. Konnaxion is optional connected intelligence. Smart Vote may inform Assemblées but never replaces them. ``` ## 2. Naming rules ### 2.1 Site name ```text Univers-Cité King Klown — Moodle Campus ``` Short name: ```text UCKK-Moodle ``` Public description: ```text UCKK-Moodle is the Moodle-based campus for the Univers-Cité King Klown, an experimental learning city and internal recognition environment. ``` ### 2.2 Forbidden wording Do not use these labels in public or student-facing UI unless formal accreditation exists: ```text official university degree state-accredited bachelor's degree public diploma equivalent recognized university credit ``` Use instead: ```text internal recognition UCKK pathway UCKK badge experimental learning program portfolio-based certification internal baccalauréat ``` ### 2.3 Component naming rule Moodle component names must match their physical plugin paths exactly. | Path | Component | |---|---| | `local/uckk` | `local_uckk` | | `course/format/uckk` | `format_uckk` | | `theme/uckk` | `theme_uckk` | | `blocks/uckk_dashboard` | `block_uckk_dashboard` | | `mod/uckkchallenge` | `mod_uckkchallenge` | | `mod/uckkassembly` | `mod_uckkassembly` | | `mod/uckkarchive` | `mod_uckkarchive` | | `admin/tool/uckkseed` | `tool_uckkseed` | | `admin/tool/uckkintegrity` | `tool_uckkintegrity` | | `report/uckk` | `report_uckk` | | `ai/provider/uckk` | `aiprovider_uckk` | A plugin is not installable until `version.php`, language strings, capabilities, service declarations, tests, and namespaces use the same component name consistently. ### 2.4 Operating-mode naming rule Use these operating-mode names consistently: | Name | Meaning | Required behavior | |---|---|---| | Standalone mode | UCKK-Moodle running without Konnaxion | Must install, seed, teach, deliberate, archive, report, and enforce permissions without Konnaxion | | Konnaxion-connected mode | UCKK-Moodle with Konnaxion bridge enabled | May add Smart Vote readings, EkoH/advisory signals, external mappings, sync logs, and better cross-module organization | Forbidden wording: ```text Konnaxion is required for UCKK-Moodle. Smart Vote is required for Assemblées. UCKK-Moodle is incomplete without Konnaxion. Konnaxion decides Moodle outcomes. Smart Vote publishes final Assembly decisions. ``` Use instead: ```text Konnaxion is an optional connected-mode integration. Smart Vote is an optional connected-mode reading. UCKK-Moodle remains functional in standalone mode. Assemblées decide; Smart Vote may inform. Archives preserve both readings and decisions when connected mode is used. ``` ## 3. Glossary for implementation | Term | Implementation meaning | |---|---| | Joueur | Moodle user enrolled as learner; also a UCKK profile state | | Joueur lucide | Badge/status earned through evidence | | Mentor | Teacher role with course and challenge evaluation capabilities | | Bâtisseur | Badge/profile distinction, not a default Moodle system role | | Archiviste | Restricted role/capability set for archive validation | | Inquisiteur | Restricted integrity reviewer, not global administrator | | Défi | Dedicated activity instance: `mod_uckkchallenge` | | Assemblée | Dedicated activity instance: `mod_uckkassembly` | | Archive | Dedicated activity instance: `mod_uckkarchive` plus cross-plugin evidence store | | Kristal pédagogique | Structured knowledge item stored in archive, glossary, or local UCKK registry | | Preuve | File, text, link, observation, decision, grade, or archive item supporting competence | | Portfolio | Aggregated evidence map attached to a Joueur | | Tronc commun | Mandatory course set seeded by `tool_uckkseed` | | Voie UCKK | Internal pathway composed of Moodle categories/courses/competencies/badges | | kOA cycle | Connaître → Choisir → Agir → Se souvenir | | Standalone mode | Core UCKK-Moodle operating mode with Konnaxion disabled or absent | | Konnaxion-connected mode | Optional operating mode where UCKK-Moodle connects to Konnaxion through Moodle-controlled settings, services, capabilities, logs, privacy coverage, and tests | | Konnaxion bridge | Moodle-side integration layer owned by `local_uckk` when connected mode is enabled | | Konnaxion mapping | Moodle-side mapping between a Moodle object/user/context and a Konnaxion object/user/context; never a permission grant by itself | | EkoH signal | External advisory expertise, ethics, reputation, or weighting signal from Konnaxion; never final Moodle authority | | Smart Vote reading | Optional weighted or computed reading from Konnaxion, displayed inside an Assembly workflow as decision support only | | Smart Vote snapshot | Moodle-side preserved copy or reference of a Smart Vote reading with method, provenance, visibility, contestation status, and archive linkage where applicable | | Assembly decision | Human/institutional Moodle-side decision published through `mod_uckkassembly` with capability checks and archive provenance | | Page controller | PHP entry point that loads Moodle config, checks login, resolves context, checks capabilities, processes input, and renders a page | | AMD module | JavaScript-only UI module under `amd/src`; it must not contain PHP page-controller code | | Service class | Namespaced class under `classes/external`, `classes/local`, or another appropriate `classes/` namespace that contains reusable business logic | | Privacy provider | `classes/privacy/provider.php` implementation declaring, exporting, and deleting personal data where required | | Acceptance gate | A documented pass/fail check before install, testing, or release | | Core acceptance gate | Pass/fail check for standalone UCKK-Moodle | | Connected acceptance gate | Pass/fail check for optional Konnaxion-connected features | ## 4. Domain rules ### Rule D1 — Moodle is the campus, not the movement Moodle implements the UCKK campus. It can teach and connect to kOA, but it must not pretend to be the whole kOA movement. ### Rule D2 — UCKK is an educational institution, not the whole infrastructure UCKK can use, teach, document, and partly integrate the kOA Digital Ecosystem. Moodle must not absorb all kOA infrastructure concepts into LMS objects unless there is a direct pedagogical or governance purpose. ### Rule D3 — King Klown is narrative power, not institutional sovereignty King Klown can appear in theme, challenge names, visual identity, onboarding, and public-facing prompts. King Klown must not override the Inquisiteur, Assemblées, evidence, or procedural rules. ### Rule D4 — The Inquisiteur is a guardrail, not arbitrary power The Inquisiteur validates, contests, pauses, corrects, and documents. The role must be permission-limited, auditable, and contestable. ### Rule D5 — Assemblées produce documented decisions An Assembly is not a chat room. It has motions, arguments, objections, amendments, votes/readings, decisions, minutes, and archive records. ### Rule D6 — Archives preserve memory with provenance Archive items must include author, context, source, date, version, visibility, evidence relation, and integrity state. ### Rule D7 — AI is non-sovereign AI features can clarify, summarize, map, draft, and detect uncertainty. AI outputs are never final decisions, final grades, final integrity judgments, or final evidence validation. ### Rule D8 — Symbolic language never overrides Moodle security Symbolic titles, narrative labels, and UCKK statuses must never be treated as implicit Moodle authority. Permissions must be represented through explicit Moodle capabilities, contexts, role assignments, and service checks. ### Rule D9 — Konnaxion is optional connected intelligence, not the Moodle campus UCKK-Moodle must install, seed, teach, deliberate, archive, report, and enforce permissions without Konnaxion. When Konnaxion-connected mode is enabled, Konnaxion may provide Smart Vote readings, EkoH/advisory signals, external mappings, analytics, and cross-module organization. These signals remain external or imported readings inside Moodle. They must not become enrolment authority, role authority, capability authority, academic authority, archive authority, integrity authority, or final Assembly authority. Canonical Smart Vote rule: ```text Konnaxion computes Smart Vote readings. UCKK-Moodle owns Assembly decisions. Archives preserve both, with provenance and contestability. ``` ### Rule D10 — External systems never write Moodle authority directly External systems, including Konnaxion, must not write directly into Moodle source tables or bypass Moodle services, permissions, privacy providers, events, logs, archive provenance, or integrity review. Moodle-side integration records must be created through documented Moodle services, capability checks, state machines, and privacy-aware storage. ## 5. Object ownership map | Object | Owner plugin | Notes | |---|---|---| | UCKK program | `local_uckk` | Canonical registry | | UCKK pathway | `local_uckk` | Links courses, competencies, badges | | UCKK course section layout | `format_uckk` | Course structure | | Challenge | `mod_uckkchallenge` | Full activity workflow | | Assembly | `mod_uckkassembly` | Full deliberation workflow | | Archive item | `mod_uckkarchive` | Evidence, decisions, Kristals | | Integrity case | `tool_uckkintegrity` | Cross-plugin case handling | | Dashboard view | `block_uckk_dashboard` | User-facing summary | | Reports | `report_uckk` | Institutional visibility | | Seed data | `tool_uckkseed` | Installation and idempotent provisioning | | AI provider | `aiprovider_uckk` | External AI bridge | | Visual identity | `theme_uckk` | No business logic | | Konnaxion bridge settings | `local_uckk` | Optional connected-mode settings and service configuration; disabled by default | | Konnaxion identity/object mappings | `local_uckk` | Optional connected-mode mapping records; never grant Moodle authority by themselves | | Smart Vote target mapping | `mod_uckkassembly` | Optional connected-mode Assembly-to-Konnaxion target linkage | | Smart Vote reading snapshot | `mod_uckkassembly` | Optional connected-mode reading record; never final decision | | Smart Vote archived memory | `mod_uckkarchive` | Preserves connected-mode readings and final Assembly decisions separately with provenance | | Smart Vote integrity review | `tool_uckkintegrity` | Reviews contested, anomalous, invalidated, privacy-sensitive, or superseded readings | | Smart Vote reports | `report_uckk` | Displays permission-filtered connected-mode readings and exports where enabled | ## 6. Implementation boundary rules These rules prevent conceptual boundaries from becoming code errors. ### Rule I1 — File type boundaries are strict ```text [ ] PHP page controllers live in .php files and start with component = 'mod_uckkarchive'; ``` A plugin must never declare another plugin’s component name. ## 4. Dependency graph ```text theme_uckk └── no hard dependency except Moodle core format_uckk └── local_uckk block_uckk_dashboard ├── local_uckk ├── mod_uckkchallenge ├── mod_uckkassembly ├── mod_uckkarchive └── tool_uckkintegrity mod_uckkchallenge ├── local_uckk ├── mod_uckkarchive └── tool_uckkintegrity mod_uckkassembly ├── local_uckk ├── mod_uckkarchive └── tool_uckkintegrity mod_uckkarchive └── local_uckk tool_uckkseed ├── local_uckk ├── format_uckk ├── mod_uckkchallenge ├── mod_uckkassembly ├── mod_uckkarchive ├── block_uckk_dashboard ├── tool_uckkintegrity └── report_uckk tool_uckkintegrity ├── local_uckk ├── mod_uckkarchive ├── mod_uckkchallenge └── mod_uckkassembly report_uckk ├── local_uckk ├── mod_uckkchallenge ├── mod_uckkassembly ├── mod_uckkarchive └── tool_uckkintegrity aiprovider_uckk └── local_uckk ``` Dependencies must be declared in each plugin’s `version.php` when the plugin cannot operate without another UCKK component. Konnaxion must not appear as a required plugin dependency for standalone mode. Konnaxion support is represented as optional settings, optional services, optional scheduled tasks, optional events, and optional tests inside the existing UCKK plugin suite. If connected mode is enabled, `local_uckk` owns the Konnaxion bridge surface and other plugins consume it through Moodle-side services and events. If connected mode is disabled, the same plugins must continue to install and operate without Konnaxion credentials, mappings, Smart Vote snapshots, or Konnaxion sync logs. Dependency declarations must be version-aware and upgrade-safe. ## 5. Plugin naming and physical paths Use Moodle component naming strictly. These are the canonical Moodle installation paths: ```text theme_uckk → theme/uckk format_uckk → course/format/uckk local_uckk → local/uckk block_uckk_dashboard → blocks/uckk_dashboard mod_uckkchallenge → mod/uckkchallenge mod_uckkassembly → mod/uckkassembly mod_uckkarchive → mod/uckkarchive tool_uckkseed → admin/tool/uckkseed tool_uckkintegrity → admin/tool/uckkintegrity report_uckk → report/uckk aiprovider_uckk → ai/provider/uckk ``` The development repository may contain packaging scripts, documentation, presets, and tools, but the installable plugin code must resolve to the paths above. Do not invent alternate plugin roots such as: ```text plugins/mod/uckkarchive plugins/local/uckk plugins/theme/uckk ``` unless those directories are only packaging/staging directories and are copied into the canonical Moodle paths during build. ## 6. Required plugin file structure Each plugin must use Moodle’s expected structure for its type. Minimum common structure: ```text version.php lang/en/*.php lang/fr/*.php db/access.php db/install.xml when the plugin owns tables db/upgrade.php when the plugin owns schema evolution classes/ classes/privacy/provider.php tests/ ``` When relevant, plugins must also include: ```text settings.php lib.php locallib.php db/services.php db/tasks.php db/events.php classes/event/* classes/external/* classes/form/* classes/output/* classes/task/* amd/src/*.js templates/*.mustache styles.css or scss/* tests/behat/*.feature ``` Generated code is not acceptable until referenced classes exist. A PHP file may reference a namespaced class only if the matching file exists under `classes/` or is provided by Moodle core. Examples: ```text mod_uckkarchive\form\archive_item_form → mod/uckkarchive/classes/form/archive_item_form.php mod_uckkarchive\event\archive_item_created → mod/uckkarchive/classes/event/archive_item_created.php mod_uckkarchive\external\create_item → mod/uckkarchive/classes/external/create_item.php local_uckk\task\recalculate_pathways → local/uckk/classes/task/recalculate_pathways.php ``` ## 7. Filetype correctness rule Every file must contain code for its declared filetype. Required rules: ```text *.php → PHP only; must start with theme_uckk course/format/uckk => format_uckk local/uckk => local_uckk blocks/uckk_dashboard => block_uckk_dashboard mod/uckkchallenge => mod_uckkchallenge mod/uckkassembly => mod_uckkassembly mod/uckkarchive => mod_uckkarchive admin/tool/uckkseed => tool_uckkseed admin/tool/uckkintegrity => tool_uckkintegrity report/uckk => report_uckk ai/provider/uckk => aiprovider_uckk ``` Package names, language component names, capability prefixes, service names, event namespaces, privacy providers, and tests must use the same component identity. ### 0.3 Required class layer A plugin is not complete if it only contains procedural controllers, `lib.php`, templates, and AMD files. When the plugin declares services, forms, events, observers, privacy metadata, scheduled tasks, renderables, or business logic, it must include matching autoloaded classes under `classes/`. Use these directories where relevant: ```text classes/external/ classes/form/ classes/event/ classes/local/ classes/output/ classes/privacy/provider.php classes/task/ classes/table/ classes/reportbuilder/ classes/observer.php or classes/observer/ classes/hook_listener.php classes/service/ ``` ### 0.4 Page, service, and capability contract Every PHP page and external service must explicitly document and enforce: ```text required login state context level required capability allowed roles/archetypes read/write nature AJAX/mobile exposure, if any privacy impact main table ownership Konnaxion/Smart Vote boundary, if relevant important events emitted ``` ### 0.5 Test contract Every plugin must include tests matching its responsibilities. ```text tests/*_test.php for PHP unit/integration coverage tests/behat/*.feature for major user workflows tests/fixtures/ for reusable test records where needed tests/external/*_test.php for web services where needed ``` ### 0.6 Operating-mode variables These variables are binding for this document and must be used when separating core plugin obligations from optional Konnaxion-connected obligations. | Variable | Canonical value | Rule | |---|---|---| | `OPERATING_MODE_STANDALONE` | `standalone_core` | UCKK-Moodle installs, seeds, teaches, deliberates, archives, reports, and passes core tests without Konnaxion. | | `OPERATING_MODE_KONNAXION_CONNECTED` | `connected_konnaxion` | Optional profile where Konnaxion bridge, Smart Vote readings, EkoH/advisory signals, mappings, sync logs, and connected reports are enabled. | | `KONNAXION_REQUIRED_FOR_CORE` | `false` | No plugin may make Konnaxion a hard dependency for standalone install or ordinary UCKK workflows. | | `SMART_VOTE_REQUIRED_FOR_CORE` | `false` | Assemblies, archives, reports, integrity review, and seed operations must work without Smart Vote. | | `KONNAXION_DEFAULT_STATE` | `disabled` | Konnaxion bridge settings, services, tasks, UI panels, and reports are hidden or fail closed until enabled. | | `SMART_VOTE_DEFAULT_STATE` | `disabled_until_connected` | Smart Vote request/import/report actions are available only in connected mode and only with explicit Moodle capabilities. | | `CORE_RELEASE_GATE` | `standalone_core_install_and_workflows_pass` | Core acceptance cannot require Konnaxion credentials, endpoints, mappings, Smart Vote snapshots, or Konnaxion reports. | | `CONNECTED_RELEASE_GATE` | `konnaxion_connected_profile_passes` | Connected acceptance applies only when Konnaxion/Smart Vote features are enabled for that release profile. | ### 0.7 Canonical alignment variables This document consumes the canonical alignment variables defined by `00_master_execution_doctrine.md`. Plugin specifications must use these names consistently in code generation, tests, services, events, capabilities, privacy providers, seed presets, and reports. #### Document variables | Variable | Canonical value | Rule | | ----------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------- | | `DOC_00` | `00_master_execution_doctrine.md` | Root doctrine and correction authority. | | `DOC_01` | `01_domain_boundaries_and_glossary.md` | Domain vocabulary and forbidden/allowed wording. | | `DOC_02` | `02_distribution_architecture.md` | Plugin distribution, dependency direction, and integration layer. | | `DOC_03` | `03_plugin_specifications.md` | Plugin implementation contract. | | `DOC_04` | `04_data_model_and_storage.md` | Table ownership, enums, state machines, and storage constraints. | | `DOC_05` | `05_roles_permissions_and_security.md` | Capability and access-control registry. | | `DOC_06` | `06_pedagogy_courses_competencies_badges.md` | Courses, competencies, evidence, and badge rules. | | `DOC_07` | `07_challenges_and_assemblies.md` | Challenge, Assembly, Smart Vote, decision, and contestation workflows. | | `DOC_08` | `08_integrity_archives_and_privacy.md` | Archive, privacy, retention, redaction, and integrity safeguards. | | `DOC_09` | `09_integrations_reporting_delivery.md` | Integration contracts, reports, exports, and delivery checks. | | `DOC_10` | `10_konnaxion_smart_vote_integration_contract.md` | Optional connected-mode Konnaxion Smart Vote integration contract. | | `LEGACY_DOC_10` | `10_implementation_correction_plan.md` | Deprecated. Must not be used as the active product-tree target. | #### Boundary variables | Variable | Canonical value | Rule | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- | | `SOURCE_FAMILY_KONNAXION` | `Konnaxion external source family` | External source of truth for Konnaxion-side Smart Vote objects and semantics. | | `EXTERNAL_SYSTEM_KONNAXION` | `Konnaxion` | External system integrated through Moodle services only. | | `SMART_VOTE_CANONICAL_RULE` | `Konnaxion computes Smart Vote readings. UCKK-Moodle owns Assembly decisions. Archives preserve both, with provenance and contestability.` | Must be preserved in every plugin that touches Smart Vote. | | `SMART_VOTE_AUTHORITY` | `computed_reading_only` | Smart Vote may inform; it must not decide, award, validate, sanction, or close contestations. | | `ASSEMBLY_AUTHORITY` | `human_institutional_decision` | Final Assembly decisions belong to Moodle-side Assembly workflow and permissions. | | `ARCHIVE_AUTHORITY` | `provenance_and_contestation_memory` | Archives preserve source, snapshot, decision, minority report, and contestation trail. | | `DIRECT_WRITE_RULE` | `external_systems_never_write_moodle_source_tables` | Konnaxion must not write directly into Moodle source tables. | | `PERMISSION_RULE` | `moodle_capabilities_remain_authoritative` | External roles, labels, or identifiers never grant Moodle authority by themselves. | #### Plugin ownership variables | Variable | Canonical owner | Responsibilities | | ---------------------------- | -------------------- | -------------------------------------------------------------------------------------------------------------------- | | `KONNAXION_BRIDGE_OWNER` | `local_uckk` | Configuration, authentication settings, endpoint client, object mapping, sync logs, shared integration services. | | `SMART_VOTE_WORKFLOW_OWNER` | `mod_uckkassembly` | Smart Vote reading requests, vote-target mapping, snapshots, review, contestation, and Assembly linkage. | | `ASSEMBLY_DECISION_OWNER` | `mod_uckkassembly` | Motions, deliberation, decision publication, minority report, and decision contestability. | | `SMART_VOTE_ARCHIVE_OWNER` | `mod_uckkarchive` | Archive records and file areas for Smart Vote snapshots, decisions, minutes, and provenance packages. | | `SMART_VOTE_REPORT_OWNER` | `report_uckk` | Smart Vote reports, institutional exports, filters, and privacy-aware visibility. | | `SMART_VOTE_INTEGRITY_OWNER` | `tool_uckkintegrity` | Integrity warnings, contested readings, correction cases, and restricted review workflows. | | `SMART_VOTE_SEED_OWNER` | `tool_uckkseed` | Idempotent presets for capabilities, mappings, report definitions, and integration defaults. | | `SMART_VOTE_PRIVACY_OWNER` | every storing plugin | Each plugin that stores personal data owns its privacy provider, export, delete, anonymisation, and retention tests. | #### Konnaxion object variables | Variable | Canonical value | Moodle-side use | | -------------------------------------- | -------------------- | ---------------------------------------------------------------------------- | | `KONNAXION_OBJECT_VOTE` | `Vote` | External vote object mapped to a Moodle-side vote target or reading source. | | `KONNAXION_OBJECT_VOTE_MODALITY` | `VoteModality` | External voting modality/method mapped to a Moodle-side reading method. | | `KONNAXION_OBJECT_VOTE_RESULT` | `VoteResult` | External result mapped into a Moodle-side Smart Vote reading snapshot. | | `KONNAXION_OBJECT_INTEGRATION_MAPPING` | `IntegrationMapping` | External mapping object mirrored by Moodle-side mapping tables. | | `KONNAXION_EXTERNAL_ID_FIELD` | `externalid` | Stores the Konnaxion identifier; never stores secrets. | | `KONNAXION_EXTERNAL_TYPE_FIELD` | `externaltype` | Stores the Konnaxion object type. | | `KONNAXION_SOURCE_VERSION_FIELD` | `sourceversion` | Stores the external source version, revision, or timestamp where available. | | `KONNAXION_SYNC_STATUS_FIELD` | `syncstatus` | Stores Moodle-side sync state using `KONNAXION_SYNC_STATUS_ENUM`. | | `KONNAXION_PROVENANCE_HASH_FIELD` | `provenancehash` | Stores integrity hash for imported snapshots or mapped records where needed. | #### Moodle-side table variables | Variable | Canonical table | Owner | Purpose | | ------------------------------- | ------------------------------ | ------------------ | ---------------------------------------------------------------------------------------------- | | `TABLE_KONNAXION_USER_MAP` | `local_uckk_kx_user_map` | `local_uckk` | Maps Moodle users to Konnaxion identities without exposing unnecessary external personal data. | | `TABLE_KONNAXION_OBJECT_MAP` | `local_uckk_kx_object_map` | `local_uckk` | Maps Moodle objects to Konnaxion objects. | | `TABLE_KONNAXION_SYNC_LOG` | `local_uckk_kx_sync_log` | `local_uckk` | Logs sync attempts, failures, retries, endpoint responses, and idempotency keys. | | `TABLE_SMART_VOTE_TARGET_MAP` | `uckkassembly_kx_vote_target` | `mod_uckkassembly` | Maps Assembly motions, decisions, or deliberation objects to Konnaxion vote targets. | | `TABLE_SMART_VOTE_SNAPSHOT` | `uckkassembly_sv_snapshot` | `mod_uckkassembly` | Stores Moodle-side immutable Smart Vote reading snapshots. | | `TABLE_SMART_VOTE_RESULT_AUDIT` | `uckkassembly_sv_result_audit` | `mod_uckkassembly` | Stores review, correction, contestation, and supersession trail for Smart Vote results. | The abbreviation `kx` is allowed only in table and internal variable names. User-facing documentation and UI must use `Konnaxion`. #### Smart Vote field variables | Variable | Canonical field/key | Rule | | ------------------------ | ------------------------------ | ---------------------------------------------------------------------------- | | `SV_RAW_DATA` | `raw_data` | Imported or referenced source facts before interpretation. | | `SV_READING_METHOD` | `reading_method` | The declared method, modality, weighting, or algorithmic reading rule. | | `SV_COMPUTED_READING` | `computed_reading` | The non-sovereign Smart Vote output. | | `SV_EXPERTISE_WEIGHT` | `expertise_weight` | Any weighted-reading factor; personal or sensitive where linkable to a user. | | `SV_HUMAN_DECISION` | `human_institutional_decision` | Moodle-side Assembly decision; must not be overwritten by Smart Vote. | | `SV_MINORITY_REPORT` | `minority_report` | Documented minority position or dissenting signal. | | `SV_INTEGRITY_WARNING` | `integrity_warning` | Warning or flag that may open integrity review but is not itself a sanction. | | `SV_CONTESTATION_STATUS` | `contestation_status` | Contestation state for the snapshot or decision linkage. | | `SV_ARCHIVE_ITEM_ID` | `archiveitemid` | Link to preserved archive item when archived. | #### State variables | Variable | Allowed values | Owner | | --------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------ | | `KONNAXION_SYNC_STATUS_ENUM` | `queued`, `running`, `succeeded`, `failed`, `retry_waiting`, `skipped`, `disabled` | `local_uckk` | | `KONNAXION_MAPPING_STATUS_ENUM` | `draft`, `active`, `suspended`, `superseded`, `archived`, `invalidated` | `local_uckk` | | `SMART_VOTE_TARGET_STATUS_ENUM` | `draft`, `mapped`, `active`, `closed`, `archived`, `contested` | `mod_uckkassembly` | | `SMART_VOTE_SNAPSHOT_STATUS_ENUM` | `imported`, `under_review`, `accepted_as_reading`, `contested`, `superseded`, `archived`, `invalidated` | `mod_uckkassembly` | | `SMART_VOTE_AUDIT_STATUS_ENUM` | `recorded`, `reviewed`, `corrected`, `contested`, `resolved` | `mod_uckkassembly` | #### Capability variables | Variable | Canonical capability | Owner | | ----------------------------- | ----------------------------------- | ------------------ | | `CAP_MANAGE_KONNAXION` | `local/uckk:managekonnaxion` | `local_uckk` | | `CAP_MAP_KONNAXION_OBJECTS` | `local/uckk:mapkonnaxionobjects` | `local_uckk` | | `CAP_VIEW_KONNAXION_LOGS` | `local/uckk:viewkonnaxionlogs` | `local_uckk` | | `CAP_REQUEST_SMART_VOTE` | `mod/uckkassembly:requestsmartvote` | `mod_uckkassembly` | | `CAP_VIEW_SMART_VOTE` | `mod/uckkassembly:viewsmartvote` | `mod_uckkassembly` | | `CAP_REVIEW_SMART_VOTE` | `mod/uckkassembly:reviewsmartvote` | `mod_uckkassembly` | | `CAP_CONTEST_SMART_VOTE` | `mod/uckkassembly:contestsmartvote` | `mod_uckkassembly` | | `CAP_ARCHIVE_SMART_VOTE` | `mod/uckkarchive:archivesmartvote` | `mod_uckkarchive` | | `CAP_VIEW_SMART_VOTE_REPORTS` | `report/uckk:viewsmartvotereports` | `report_uckk` | #### Service and event variables | Variable | Canonical name | Owner | | ------------------------------------- | ------------------------------------------------------ | ------------------ | | `SERVICE_CREATE_KONNAXION_MAPPING` | `local_uckk_create_konnaxion_mapping` | `local_uckk` | | `SERVICE_GET_KONNAXION_MAPPING` | `local_uckk_get_konnaxion_mapping` | `local_uckk` | | `SERVICE_SYNC_KONNAXION` | `local_uckk_sync_konnaxion` | `local_uckk` | | `SERVICE_REQUEST_SMART_VOTE_READING` | `mod_uckkassembly_request_smart_vote_reading` | `mod_uckkassembly` | | `SERVICE_IMPORT_SMART_VOTE_SNAPSHOT` | `mod_uckkassembly_import_smart_vote_snapshot` | `mod_uckkassembly` | | `SERVICE_CONTEST_SMART_VOTE_SNAPSHOT` | `mod_uckkassembly_contest_smart_vote_snapshot` | `mod_uckkassembly` | | `SERVICE_GET_SMART_VOTE_REPORT` | `report_uckk_get_smart_vote_report` | `report_uckk` | | `EVENT_KONNAXION_MAPPING_CREATED` | `local_uckk\event\konnaxion_mapping_created` | `local_uckk` | | `EVENT_KONNAXION_SYNC_COMPLETED` | `local_uckk\event\konnaxion_sync_completed` | `local_uckk` | | `EVENT_SMART_VOTE_READING_REQUESTED` | `mod_uckkassembly\event\smart_vote_reading_requested` | `mod_uckkassembly` | | `EVENT_SMART_VOTE_SNAPSHOT_IMPORTED` | `mod_uckkassembly\event\smart_vote_snapshot_imported` | `mod_uckkassembly` | | `EVENT_SMART_VOTE_SNAPSHOT_CONTESTED` | `mod_uckkassembly\event\smart_vote_snapshot_contested` | `mod_uckkassembly` | | `EVENT_SMART_VOTE_SNAPSHOT_ARCHIVED` | `mod_uckkassembly\event\smart_vote_snapshot_archived` | `mod_uckkassembly` | #### Preset variables | Variable | Canonical preset | Required by | | --------------------------- | --------------------------------- | ------------------------------------------------------------------------- | | `PRESET_CAPABILITIES` | `presets/capabilities.json` | Roles, capabilities, tests, seed tool. | | `PRESET_STATE_MACHINES` | `presets/state_machines.json` | Workflow statuses and transitions. | | `PRESET_EVENTS` | `presets/events.json` | Event-class registry and tests. | | `PRESET_KONNAXION_MAPPINGS` | `presets/konnaxion_mappings.json` | Optional connected-mode Konnaxion object map defaults and validation fixtures. | | `PRESET_PRIVACY_RETENTION` | `presets/privacy_retention.json` | Privacy, export, deletion, anonymisation, redaction, and retention tests. | | `PRESET_EXPORTS` | `presets/exports.json` | Report/export definitions and acceptance evidence. | ## 1. `theme_uckk` ### Purpose Provide visual identity, layouts, templates, and UI language for UCKK while keeping all institutional, grading, workflow, permission, archive, integrity, Smart Vote, Konnaxion, and AI decisions outside the theme. ### Must deliver ```text theme/uckk/version.php theme/uckk/config.php theme/uckk/lib.php theme/uckk/settings.php theme/uckk/db/upgrade.php theme/uckk/lang/en/theme_uckk.php theme/uckk/lang/fr/theme_uckk.php theme/uckk/scss/ theme/uckk/scss/preset/default.scss theme/uckk/templates/ theme/uckk/layout/ theme/uckk/pix/ theme/uckk/amd/src/ theme/uckk/classes/output/ theme/uckk/classes/privacy/provider.php theme/uckk/tests/ theme/uckk/tests/behat/ theme/uckk/README.md ``` ### Features * UCKK frontpage layout. * Dashboard-friendly layout. * Course, challenge, assembly, archive visual variants. * King Klown visual layer without confusing symbolic and institutional authority. * Smart Vote labels rendered as readings, never decisions, only where connected-mode data is enabled and visible. * Konnaxion labels rendered as external-source data where shown in connected mode. * Accessibility-compliant contrast, navigation, language strings, and keyboard behavior. * French-first and English-ready UI. * Boost-compatible inheritance and fallback behavior. * SCSS-driven styling only; no legacy stylesheet dependency unless explicitly justified. ### Must not do * No grading logic. * No permission decisions beyond presentation checks already made by Moodle. * No challenge, assembly, archive, integrity, report, seed, Konnaxion, Smart Vote, or AI workflow logic. * No data ownership. * No hidden authority escalation through templates or layouts. ### Required tests ```text PHPUnit: theme callbacks, SCSS callbacks, privacy provider, output context builders. Behat: frontpage, dashboard layout, language switching, accessibility-critical navigation, and connected-mode Smart Vote reading label visibility when enabled. JS: AMD modules build cleanly through Moodle's Grunt pipeline. ``` ## 2. `format_uckk` ### Purpose Define the standard UCKK course structure and course-page presentation without owning institutional records, Smart Vote records, Konnaxion records, or activity workflows. ### Default sections ```text 0. Orientation 1. Concepts 2. Matière canonique 3. Atelier 4. Preuves 5. Délibération 6. Livrable 7. Évaluation 8. Archive ``` ### Must deliver ```text course/format/uckk/version.php course/format/uckk/lib.php course/format/uckk/format.php course/format/uckk/settings.php course/format/uckk/db/access.php course/format/uckk/db/upgrade.php course/format/uckk/classes/output/ course/format/uckk/classes/local/ course/format/uckk/classes/privacy/provider.php course/format/uckk/templates/ course/format/uckk/amd/src/ course/format/uckk/lang/en/format_uckk.php course/format/uckk/lang/fr/format_uckk.php course/format/uckk/tests/ course/format/uckk/tests/behat/ course/format/uckk/README.md ``` ### Features * UCKK section map. * Section metadata. * Evidence indicators. * Archive indicators. * Integrity warning indicators. * Smart Vote reading indicators where connected mode is enabled and readings are sourced from `mod_uckkassembly`. * Course index support. * Completion summary. * Compatibility with Moodle course editing, activity chooser, drag/drop section operations, and course backup/restore. ### Must not do * Must not store source challenge submissions. * Must not store source assembly motions, votes, readings, or decisions. * Must not store Smart Vote snapshots. * Must not store Konnaxion mappings. * Must not store archive item content. * Must not make integrity decisions. * Must not bypass Moodle course editing permissions. ### Required tests ```text PHPUnit: section map, metadata mapping, privacy provider, output builders. Behat: create UCKK course, edit sections, view indicators, preserve Moodle editing behavior. JS: course format AMD modules build and initialize only on intended regions. ``` ## 3. `local_uckk` ### Purpose Own the core institutional registry, shared services, shared navigation, component registry, and cross-plugin coordination rules. In connected mode, also own the Moodle-side Konnaxion bridge. ### Must deliver ```text local/uckk/version.php local/uckk/index.php local/uckk/canon.php local/uckk/pathways.php local/uckk/settings.php local/uckk/lib.php local/uckk/db/install.xml local/uckk/db/upgrade.php local/uckk/db/access.php local/uckk/db/services.php local/uckk/db/events.php local/uckk/db/hooks.php local/uckk/db/tasks.php local/uckk/classes/service/ local/uckk/classes/external/ local/uckk/classes/event/ local/uckk/classes/local/ local/uckk/classes/output/ local/uckk/classes/privacy/provider.php local/uckk/classes/task/ local/uckk/classes/observer/ local/uckk/classes/hook_listener.php local/uckk/templates/ local/uckk/amd/src/ local/uckk/lang/en/local_uckk.php local/uckk/lang/fr/local_uckk.php local/uckk/tests/ local/uckk/tests/behat/ local/uckk/README.md ``` ### Optional connected-mode deliverables When `OPERATING_MODE_KONNAXION_CONNECTED` is enabled, `local_uckk` must also deliver: ```text local/uckk/konnaxion.php local/uckk/classes/service/konnaxion_client.php local/uckk/classes/service/konnaxion_mapping_service.php local/uckk/classes/service/konnaxion_sync_service.php local/uckk/classes/external/create_konnaxion_mapping.php local/uckk/classes/external/get_konnaxion_mapping.php local/uckk/classes/external/sync_konnaxion.php local/uckk/classes/event/konnaxion_mapping_created.php local/uckk/classes/event/konnaxion_sync_completed.php ``` These files and classes must not be hard requirements for standalone-core workflows unless the connected profile is explicitly selected. ### Owns * Programs. * Pathways. * Symbolic roles. * Joueur profiles. * UCKK campus settings. * Shared provenance records. * Shared visibility rules. * Navigation registry. * Component registry and dependency map. ### Owns in connected mode only * Konnaxion configuration. * Konnaxion user mappings. * Konnaxion object mappings. * Konnaxion sync logs. * Shared Konnaxion endpoint client and service contract. ### Does not own * Challenge submissions. * Assembly motions, votes, Smart Vote snapshots, or decisions. * Archive item content. * Integrity case records. * AI prompt/response logs. * Assembly Smart Vote target mappings. * Assembly Smart Vote result audits. * Final Assembly decisions. When connected mode is enabled, `local_uckk` owns the Konnaxion bridge layer, not Smart Vote institutional meaning. It can authenticate to Konnaxion, map external identifiers, call endpoints, log sync state, and expose stable helper services. It must not publish Assembly decisions, overwrite Assembly records, or treat external Konnaxion identity as Moodle permission. ### Core required classes ```text local_uckk\external\* local_uckk\event\program_created local_uckk\event\pathway_assigned local_uckk\event\profile_updated local_uckk\observer\user_observer local_uckk\observer\course_observer local_uckk\observer\category_observer local_uckk\observer\completion_observer local_uckk\hook_listener local_uckk\task\* local_uckk\privacy\provider ``` ### Optional Konnaxion-connected classes Required only when `OPERATING_MODE_KONNAXION_CONNECTED` is enabled: ```text local_uckk\event\konnaxion_mapping_created local_uckk\event\konnaxion_sync_completed local_uckk\service\konnaxion_client local_uckk\service\konnaxion_mapping_service local_uckk\service\konnaxion_sync_service local_uckk\external\create_konnaxion_mapping local_uckk\external\get_konnaxion_mapping local_uckk\external\sync_konnaxion ``` ### Konnaxion bridge contract If connected mode is enabled, `local_uckk` implements `KONNAXION_BRIDGE_OWNER`. In connected mode, it must define these Moodle-side storage responsibilities in `DOC_04` and matching XMLDB tables: ```text TABLE_KONNAXION_USER_MAP = local_uckk_kx_user_map TABLE_KONNAXION_OBJECT_MAP = local_uckk_kx_object_map TABLE_KONNAXION_SYNC_LOG = local_uckk_kx_sync_log ``` In connected mode, it must define these capabilities in `db/access.php` and `DOC_05`: ```text CAP_MANAGE_KONNAXION = local/uckk:managekonnaxion CAP_MAP_KONNAXION_OBJECTS = local/uckk:mapkonnaxionobjects CAP_VIEW_KONNAXION_LOGS = local/uckk:viewkonnaxionlogs ``` In connected mode, it must expose these external services only with parameter validation, return validation, sesskey/token rules, context checks, capability checks, and privacy notes: ```text SERVICE_CREATE_KONNAXION_MAPPING = local_uckk_create_konnaxion_mapping SERVICE_GET_KONNAXION_MAPPING = local_uckk_get_konnaxion_mapping SERVICE_SYNC_KONNAXION = local_uckk_sync_konnaxion ``` In connected mode, it must emit these events without leaking secrets or unnecessary personal data in event descriptions: ```text EVENT_KONNAXION_MAPPING_CREATED = local_uckk\event\konnaxion_mapping_created EVENT_KONNAXION_SYNC_COMPLETED = local_uckk\event\konnaxion_sync_completed ``` In connected mode, the Konnaxion bridge must support these sync states: ```text KONNAXION_SYNC_STATUS_ENUM = queued, running, succeeded, failed, retry_waiting, skipped, disabled KONNAXION_MAPPING_STATUS_ENUM = draft, active, suspended, superseded, archived, invalidated ``` The bridge must never write directly into `mod_uckkassembly`, `mod_uckkarchive`, `tool_uckkintegrity`, or `report_uckk` source tables. It must expose stable services that those plugins call or observe. When disabled, its tasks, UI, services, and reports must fail closed without breaking standalone-core workflows. ### Required tests ```text PHPUnit: registry, dependencies, core external services, observer behavior, privacy provider, and connected-mode Konnaxion mapping CRUD plus Konnaxion sync timeout/failure/retry/idempotency when enabled. Behat: profile/pathway screens, navigation, role-specific access, and connected-mode Konnaxion configuration visibility by capability when enabled. ``` ## 4. `block_uckk_dashboard` ### Purpose Display the Joueur and staff cockpit by aggregating state from source plugins. The block must display, not own, institutional workflow state. ### Must deliver ```text blocks/uckk_dashboard/version.php blocks/uckk_dashboard/block_uckk_dashboard.php blocks/uckk_dashboard/edit_form.php blocks/uckk_dashboard/db/access.php blocks/uckk_dashboard/db/upgrade.php blocks/uckk_dashboard/classes/output/ blocks/uckk_dashboard/classes/local/ blocks/uckk_dashboard/classes/privacy/provider.php blocks/uckk_dashboard/templates/ blocks/uckk_dashboard/amd/src/ blocks/uckk_dashboard/lang/en/block_uckk_dashboard.php blocks/uckk_dashboard/lang/fr/block_uckk_dashboard.php blocks/uckk_dashboard/tests/ blocks/uckk_dashboard/tests/behat/ blocks/uckk_dashboard/README.md ``` ### Dashboard cards ```text My pathway Tronc commun My competencies My badges My challenges My assemblies My Smart Vote readings, when connected mode is enabled My archive My integrity feedback My deadlines My portfolio ``` ### Role-specific variants | Viewer | Dashboard emphasis | | ------------ | ---------------------------------------------------------------- | | Joueur | Progress, evidence, tasks, permitted Smart Vote readings | | Mentor | Submissions, evaluation, cohorts, Assembly participation signals | | Archiviste | Items awaiting validation, Smart Vote snapshots awaiting archive when connected mode is enabled | | Inquisiteur | Open integrity cases, contested readings where such readings exist | | Gestionnaire | Campus reports, configuration, and Konnaxion sync health when connected mode is enabled | ### Must not do * Must not create source records. * Must not mutate challenge, assembly, archive, or integrity state. * Must not expose restricted archive, Smart Vote, Konnaxion, or integrity data without capability checks. * Must not compute grades. * Must not compute Smart Vote readings or mutate Smart Vote snapshots. ### Required tests ```text PHPUnit: card data providers, capability filtering, privacy provider, and connected-mode Smart Vote card filtering when enabled. Behat: dashboard visible cards by role, hidden restricted cards by role, block config, and connected-mode Smart Vote card visibility when enabled. JS: refresh/dashboard modules build and degrade safely. ``` ## 5. `mod_uckkchallenge` ### Purpose Dedicated Moodle activity module for Défis King Klown. ### Must deliver ```text mod/uckkchallenge/version.php mod/uckkchallenge/lib.php mod/uckkchallenge/locallib.php mod/uckkchallenge/mod_form.php mod/uckkchallenge/view.php mod/uckkchallenge/submit.php mod/uckkchallenge/archive.php mod/uckkchallenge/integrity.php mod/uckkchallenge/db/install.xml mod/uckkchallenge/db/upgrade.php mod/uckkchallenge/db/access.php mod/uckkchallenge/db/events.php mod/uckkchallenge/db/services.php mod/uckkchallenge/classes/external/ mod/uckkchallenge/classes/form/ mod/uckkchallenge/classes/event/ mod/uckkchallenge/classes/local/ mod/uckkchallenge/classes/output/ mod/uckkchallenge/classes/privacy/provider.php mod/uckkchallenge/classes/task/ mod/uckkchallenge/templates/ mod/uckkchallenge/amd/src/ mod/uckkchallenge/lang/en/uckkchallenge.php mod/uckkchallenge/lang/fr/uckkchallenge.php mod/uckkchallenge/tests/ mod/uckkchallenge/tests/behat/ mod/uckkchallenge/README.md ``` ### Workflow states ```text draft published open submitted under_review integrity_review revision_required validated archived contested invalidated closed ``` ### Core features * Challenge statement. * Rules. * Corridors of action. * Evidence requirements. * Individual or team submissions. * Mentor evaluation. * Integrity review. * Archive export. * Badge and competency links. * Optional Assembly reference where a challenge requires deliberation. * Optional read-only display of Assembly state; Smart Vote state only when connected mode is enabled and authorized. ### Required classes ```text mod_uckkchallenge\external\* mod_uckkchallenge\form\submission_form mod_uckkchallenge\form\review_form mod_uckkchallenge\event\challenge_created mod_uckkchallenge\event\submission_created mod_uckkchallenge\event\submission_reviewed mod_uckkchallenge\event\challenge_archived mod_uckkchallenge\local\state_machine mod_uckkchallenge\local\archive_exporter mod_uckkchallenge\local\integrity_bridge mod_uckkchallenge\output\* mod_uckkchallenge\privacy\provider ``` ### Must not do * Must not own Assembly decisions. * Must not own Smart Vote snapshots. * Must not own Konnaxion mappings. * Must not award badges directly without competency, evidence, integrity, and archive rules. * Must not bypass archive or integrity workflow. * Must not treat a Smart Vote reading as validation of challenge evidence. ### Required tests ```text PHPUnit: state machine, submission lifecycle, review, archive handoff, integrity handoff, privacy provider. Behat: create challenge, submit evidence, review, request revision, validate, archive, contest. ``` ## 6. `mod_uckkassembly` ### Purpose Dedicated Moodle activity module for Assemblées. In standalone-core mode it owns motions, deliberation, ordinary votes/readings, decisions, minutes, contestations, and archive linkage. In connected mode it also owns the Moodle-side Smart Vote workflow, vote-target mapping, result snapshots, review, contestation, and decision linkage. ### Must deliver ```text mod/uckkassembly/version.php mod/uckkassembly/lib.php mod/uckkassembly/locallib.php mod/uckkassembly/mod_form.php mod/uckkassembly/view.php mod/uckkassembly/propose.php mod/uckkassembly/contest.php mod/uckkassembly/decision.php mod/uckkassembly/minutes.php mod/uckkassembly/vote.php mod/uckkassembly/db/install.xml mod/uckkassembly/db/upgrade.php mod/uckkassembly/db/access.php mod/uckkassembly/db/events.php mod/uckkassembly/db/services.php mod/uckkassembly/classes/external/ mod/uckkassembly/classes/form/ mod/uckkassembly/classes/event/ mod/uckkassembly/classes/local/ mod/uckkassembly/classes/output/ mod/uckkassembly/classes/privacy/provider.php mod/uckkassembly/classes/task/ mod/uckkassembly/templates/ mod/uckkassembly/amd/src/ mod/uckkassembly/lang/en/uckkassembly.php mod/uckkassembly/lang/fr/uckkassembly.php mod/uckkassembly/tests/ mod/uckkassembly/tests/behat/ mod/uckkassembly/README.md ``` ### Optional connected-mode deliverables Required only when Konnaxion-connected mode is enabled: ```text mod/uckkassembly/smartvote.php mod/uckkassembly/smartvote_review.php mod/uckkassembly/classes/external/request_smart_vote_reading.php mod/uckkassembly/classes/external/import_smart_vote_snapshot.php mod/uckkassembly/classes/external/contest_smart_vote_snapshot.php mod/uckkassembly/classes/form/smart_vote_request_form.php mod/uckkassembly/classes/form/smart_vote_contestation_form.php mod/uckkassembly/classes/local/smart_vote_service.php mod/uckkassembly/classes/local/smart_vote_repository.php mod/uckkassembly/classes/local/smart_vote_snapshot_repository.php mod/uckkassembly/classes/local/smart_vote_result_audit_repository.php ``` These files must not be required to create ordinary Assemblies, record ordinary votes/readings, publish human decisions, write minutes, contest decisions, or archive Assembly records in standalone-core mode. ### Assembly types ```text savoirs defis joueurs batisseurs inquisiteurs grand_jeu ``` ### Core features * Motions. * Structured arguments. * Objections. * Amendments. * Ordinary votes/readings. * Decision publication. * Minority report. * Contestation. * Minutes. * Archive export. ### Optional connected-mode features * Konnaxion Smart Vote reading request. * Smart Vote target mapping. * Smart Vote snapshot import. * Smart Vote review and contestation. ### Smart Vote connected-mode state contract When connected mode is enabled, `mod_uckkassembly` owns these Smart Vote status variables: ```text SMART_VOTE_TARGET_STATUS_ENUM = draft, mapped, active, closed, archived, contested SMART_VOTE_SNAPSHOT_STATUS_ENUM = imported, under_review, accepted_as_reading, contested, superseded, archived, invalidated SMART_VOTE_AUDIT_STATUS_ENUM = recorded, reviewed, corrected, contested, resolved ``` A Smart Vote snapshot is never a final Assembly decision. The snapshot must preserve: ```text SV_RAW_DATA SV_READING_METHOD SV_COMPUTED_READING SV_EXPERTISE_WEIGHT when present SV_HUMAN_DECISION linkage when a decision exists SV_MINORITY_REPORT linkage when a minority report exists SV_INTEGRITY_WARNING when present SV_CONTESTATION_STATUS SV_ARCHIVE_ITEM_ID when archived ``` ### Optional connected-mode capabilities Required only when connected mode is enabled: ```text CAP_REQUEST_SMART_VOTE = mod/uckkassembly:requestsmartvote CAP_VIEW_SMART_VOTE = mod/uckkassembly:viewsmartvote CAP_REVIEW_SMART_VOTE = mod/uckkassembly:reviewsmartvote CAP_CONTEST_SMART_VOTE = mod/uckkassembly:contestsmartvote ``` ### Optional connected-mode services Required only when connected mode is enabled: ```text SERVICE_REQUEST_SMART_VOTE_READING = mod_uckkassembly_request_smart_vote_reading SERVICE_IMPORT_SMART_VOTE_SNAPSHOT = mod_uckkassembly_import_smart_vote_snapshot SERVICE_CONTEST_SMART_VOTE_SNAPSHOT = mod_uckkassembly_contest_smart_vote_snapshot ``` ### Optional connected-mode events Required only when connected mode is enabled: ```text EVENT_SMART_VOTE_READING_REQUESTED = mod_uckkassembly\event\smart_vote_reading_requested EVENT_SMART_VOTE_SNAPSHOT_IMPORTED = mod_uckkassembly\event\smart_vote_snapshot_imported EVENT_SMART_VOTE_SNAPSHOT_CONTESTED = mod_uckkassembly\event\smart_vote_snapshot_contested EVENT_SMART_VOTE_SNAPSHOT_ARCHIVED = mod_uckkassembly\event\smart_vote_snapshot_archived ``` ### Core required classes ```text mod_uckkassembly\external\* mod_uckkassembly\form\motion_form mod_uckkassembly\form\argument_form mod_uckkassembly\form\vote_form mod_uckkassembly\event\motion_created mod_uckkassembly\event\vote_cast mod_uckkassembly\event\decision_published mod_uckkassembly\event\minutes_archived mod_uckkassembly\local\state_machine mod_uckkassembly\local\quorum_calculator mod_uckkassembly\local\archive_exporter mod_uckkassembly\output\* mod_uckkassembly\privacy\provider ``` ### Optional connected-mode classes Required only when connected mode is enabled: ```text mod_uckkassembly\external\request_smart_vote_reading mod_uckkassembly\external\import_smart_vote_snapshot mod_uckkassembly\external\contest_smart_vote_snapshot mod_uckkassembly\form\smart_vote_request_form mod_uckkassembly\form\smart_vote_contestation_form mod_uckkassembly\event\smart_vote_reading_requested mod_uckkassembly\event\smart_vote_snapshot_imported mod_uckkassembly\event\smart_vote_snapshot_contested mod_uckkassembly\event\smart_vote_snapshot_archived mod_uckkassembly\local\smart_vote_service mod_uckkassembly\local\smart_vote_repository mod_uckkassembly\local\smart_vote_snapshot_repository mod_uckkassembly\local\smart_vote_result_audit_repository ``` ### Must not do * Must not override site-wide governance roles. * Must not hide minority reports when policy requires visibility. * Must not publish final decisions without capability and state checks. * Must not let AI become an assembly decision-maker. * Must not let Smart Vote become an Assembly decision-maker. * Must not allow Konnaxion to write directly into Assembly source tables. * Must not treat Konnaxion `VoteResult` as a final decision. * Must not overwrite minority reports, human decisions, or contestation records with computed readings. * Must not import a Smart Vote snapshot without raw data, reading method, computed reading, source version or timestamp when available, provenance hash where required, review state, and contestation state. ### Required tests ```text PHPUnit: motion lifecycle, ordinary voting/readings, quorum, decision publication, privacy provider, archive handoff, and connected-mode Smart Vote target mapping, reading request, snapshot import, review, and contestation when enabled. Behat: create assembly, propose motion, amend, vote, publish human decision, archive minutes, and connected-mode Smart Vote request/review/contestation scenarios when enabled. ``` ## 7. `mod_uckkarchive` ### Purpose Dedicated Moodle activity module for Archives, evidence preservation, provenance, versioning, and institutional memory. ### Must deliver ```text mod/uckkarchive/version.php mod/uckkarchive/lib.php mod/uckkarchive/locallib.php mod/uckkarchive/mod_form.php mod/uckkarchive/view.php mod/uckkarchive/item.php mod/uckkarchive/versioning.php mod/uckkarchive/db/install.xml mod/uckkarchive/db/upgrade.php mod/uckkarchive/db/access.php mod/uckkarchive/db/events.php mod/uckkarchive/db/services.php mod/uckkarchive/classes/external/ mod/uckkarchive/classes/form/ mod/uckkarchive/classes/event/ mod/uckkarchive/classes/local/ mod/uckkarchive/classes/output/ mod/uckkarchive/classes/privacy/provider.php mod/uckkarchive/classes/task/ mod/uckkarchive/templates/ mod/uckkarchive/amd/src/ mod/uckkarchive/lang/en/uckkarchive.php mod/uckkarchive/lang/fr/uckkarchive.php mod/uckkarchive/tests/ mod/uckkarchive/tests/behat/ mod/uckkarchive/README.md ``` ### Optional connected-mode deliverables Required only when connected mode is enabled: ```text mod/uckkarchive/smartvote.php mod/uckkarchive/classes/event/smart_vote_snapshot_archived.php mod/uckkarchive/classes/local/smart_vote_archive_service.php ``` ### Core features * Archive item creation. * Archive item validation. * Smart Vote snapshot preservation when connected mode is enabled. * Versioning. * Provenance chain. * Visibility rules. * Evidence relations. * Assembly minutes preservation. * Challenge evidence preservation. * Integrity review references. * Export package generation. ### Core required classes ```text mod_uckkarchive\external\* mod_uckkarchive\form\archive_item_form mod_uckkarchive\form\archive_validation_form mod_uckkarchive\event\archive_item_created mod_uckkarchive\event\archive_item_validated mod_uckkarchive\event\archive_item_version_created mod_uckkarchive\local\archive_repository mod_uckkarchive\local\version_repository mod_uckkarchive\local\provenance_service mod_uckkarchive\local\exporter mod_uckkarchive\output\* mod_uckkarchive\privacy\provider ``` ### Optional connected-mode classes Required only when connected mode is enabled: ```text mod_uckkarchive\event\smart_vote_snapshot_archived mod_uckkarchive\local\smart_vote_archive_service ``` ### Optional connected-mode capabilities Required only when connected mode is enabled: ```text CAP_ARCHIVE_SMART_VOTE = mod/uckkarchive:archivesmartvote ``` ### Must not do * Must not fabricate provenance. * Must not convert Smart Vote readings into final Assembly decisions. * Must not archive Konnaxion-derived data without source, method, snapshot, visibility, and contestation metadata. * Must not expose restricted evidence without capability checks. * Must not delete institutional memory without retention and redaction rules. * Must not silently change archived content after validation. ### Required tests ```text PHPUnit: archive item lifecycle, versioning, provenance, file areas, privacy provider, and connected-mode Smart Vote snapshot archival when enabled. Behat: create archive item, validate, version, preserve Assembly minutes, export package, and connected-mode Smart Vote snapshot archival when enabled. ``` ## 8. `tool_uckkseed` ### Purpose Install and update the UCKK campus structure through repeatable, idempotent seed operations. ### Must deliver ```text admin/tool/uckkseed/version.php admin/tool/uckkseed/index.php admin/tool/uckkseed/cli/seed.php admin/tool/uckkseed/cli/dryrun.php admin/tool/uckkseed/settings.php admin/tool/uckkseed/db/install.xml admin/tool/uckkseed/db/upgrade.php admin/tool/uckkseed/db/access.php admin/tool/uckkseed/db/tasks.php admin/tool/uckkseed/classes/form/ admin/tool/uckkseed/classes/local/ admin/tool/uckkseed/classes/output/ admin/tool/uckkseed/classes/privacy/provider.php admin/tool/uckkseed/classes/task/ admin/tool/uckkseed/lang/en/tool_uckkseed.php admin/tool/uckkseed/lang/fr/tool_uckkseed.php admin/tool/uckkseed/tests/ admin/tool/uckkseed/tests/behat/ admin/tool/uckkseed/README.md presets/categories.json presets/courses.json presets/cohorts.json presets/roles.json presets/capabilities.json presets/competencies.json presets/badges.json presets/reports.json presets/navigation.json presets/state_machines.json presets/events.json presets/privacy_retention.json presets/exports.json ``` ### Optional connected-mode presets Required only when connected mode is enabled: ```text presets/konnaxion_mappings.json ``` ### Seed objects * Categories. * Courses. * Cohorts. * Roles. * Capabilities. * Competency frameworks. * Badges. * Reports. * Navigation. * State machines. * Event registry. * Konnaxion mapping defaults when connected mode is enabled. * Privacy/retention defaults. * Export definitions. * Default dashboard configuration. * Standard archive templates. ### Must not do * Must not silently overwrite hand-edited records. * Must not create duplicate records on rerun. * Must not create active Konnaxion mappings without explicit admin configuration. * Must not seed Smart Vote capabilities without matching role, test, and privacy registry entries. * Must not grant unrestricted admin-like permissions to symbolic roles. * Must not seed incomplete stubs. ### Required tests ```text PHPUnit: dry-run, idempotency, dependency validation, core preset JSON validation, rollback log, and connected-mode Konnaxion preset validation when enabled. Behat: admin seed workflow, rerun idempotency, seeded campus visible, restricted seed access, and connected-mode Konnaxion preset validation when enabled. CLI: seed.php and dryrun.php execute without interactive assumptions. ``` ## 9. `tool_uckkintegrity` ### Purpose Implement the Inquisiteur workflow for integrity reviews, contested evidence, contested readings, contested decisions, AI uncertainty flags, and procedural corrections. ### Must deliver ```text admin/tool/uckkintegrity/version.php admin/tool/uckkintegrity/index.php admin/tool/uckkintegrity/case.php admin/tool/uckkintegrity/review.php admin/tool/uckkintegrity/settings.php admin/tool/uckkintegrity/db/install.xml admin/tool/uckkintegrity/db/upgrade.php admin/tool/uckkintegrity/db/access.php admin/tool/uckkintegrity/db/events.php admin/tool/uckkintegrity/db/services.php admin/tool/uckkintegrity/db/tasks.php admin/tool/uckkintegrity/classes/external/ admin/tool/uckkintegrity/classes/form/ admin/tool/uckkintegrity/classes/event/ admin/tool/uckkintegrity/classes/local/ admin/tool/uckkintegrity/classes/output/ admin/tool/uckkintegrity/classes/privacy/provider.php admin/tool/uckkintegrity/classes/task/ admin/tool/uckkintegrity/templates/ admin/tool/uckkintegrity/amd/src/ admin/tool/uckkintegrity/lang/en/tool_uckkintegrity.php admin/tool/uckkintegrity/lang/fr/tool_uckkintegrity.php admin/tool/uckkintegrity/tests/ admin/tool/uckkintegrity/tests/behat/ admin/tool/uckkintegrity/README.md ``` ### Case types * Evidence integrity. * Challenge evaluation dispute. * Assembly procedure issue. * Smart Vote integrity warning when connected mode is enabled. * Contested Konnaxion-derived reading when connected mode is enabled. * Archive provenance issue. * AI uncertainty flag. * Procedural correction. ### Core required classes ```text tool_uckkintegrity\external\* tool_uckkintegrity\form\case_form tool_uckkintegrity\form\review_form tool_uckkintegrity\event\case_opened tool_uckkintegrity\event\case_reviewed tool_uckkintegrity\event\case_closed tool_uckkintegrity\local\case_repository tool_uckkintegrity\local\review_service tool_uckkintegrity\output\* tool_uckkintegrity\privacy\provider ``` ### Optional connected-mode classes Required only when connected mode is enabled: ```text tool_uckkintegrity\local\smart_vote_integrity_service ``` ### Must not do * Must not act as a hidden administrator. * Must not convert a Smart Vote integrity warning into an automatic sanction. * Must not bypass Assembly contestation when reviewing Konnaxion-derived readings. * Must not delete or rewrite source evidence without archive/redaction rules. * Must not hide integrity actions from audit trails. * Must not resolve disputes without documented outcome and capability checks. ### Required tests ```text PHPUnit: case lifecycle, restricted access, privacy provider, and connected-mode Smart Vote warning/contested-reading review when enabled. Behat: open case, assign reviewer, review contested evidence, close with outcome, deny unauthorized access, and connected-mode contested Smart Vote reading review when enabled. ``` ## 10. `report_uckk` ### Purpose Provide institutional reporting over UCKK records without becoming the owner of source workflow data. ### Must deliver ```text report/uckk/version.php report/uckk/index.php report/uckk/settings.php report/uckk/db/access.php report/uckk/db/services.php report/uckk/db/upgrade.php report/uckk/classes/local/ report/uckk/classes/output/ report/uckk/classes/reportbuilder/ report/uckk/classes/privacy/provider.php report/uckk/templates/ report/uckk/amd/src/ report/uckk/lang/en/report_uckk.php report/uckk/lang/fr/report_uckk.php report/uckk/tests/ report/uckk/tests/behat/ report/uckk/README.md ``` ### Report families ```text joueur_progress cohort_progress program_progress competency_matrix badge_awards challenge_status assembly_decisions archive_production smart_vote_readings, when connected mode is enabled smart_vote_contestations, when connected mode is enabled konnaxion_sync_status, when connected mode is enabled integrity_cases ai_usage privacy_exports ``` ### Core required classes ```text report_uckk\local\report_repository report_uckk\local\access_filter report_uckk\output\* report_uckk\reportbuilder\datasource\* report_uckk\privacy\provider ``` ### Optional connected-mode classes Required only when connected mode is enabled: ```text report_uckk\local\smart_vote_report_repository report_uckk\external\get_smart_vote_report ``` ### Optional connected-mode capability Required only when connected mode is enabled: ```text CAP_VIEW_SMART_VOTE_REPORTS = report/uckk:viewsmartvotereports ``` ### Optional connected-mode service Required only when connected mode is enabled: ```text SERVICE_GET_SMART_VOTE_REPORT = report_uckk_get_smart_vote_report ``` ### Must not do * Must not bypass source plugin capability checks. * Must not expose personally identifiable or integrity-sensitive data through aggregate reports. * Must not mutate source records. * Must not cache restricted data without retention and invalidation rules. * Must not report Smart Vote readings as final decisions. * Must not expose Konnaxion external identifiers unless the viewer has the required capability and the report requires them. * Must not export Smart Vote data without provenance, reading method, contestation state, privacy filtering, and archive linkage where applicable. ### Required tests ```text PHPUnit: report data sources, access filtering, privacy provider, and connected-mode Smart Vote report service plus Konnaxion identifier redaction when enabled. Behat: report visibility by role, restricted report denial, export behavior, and connected-mode Smart Vote report visibility when enabled. ``` ## 11. `aiprovider_uckk` ### Purpose Bridge UCKK-Moodle to governed AI services while preserving human authority, privacy controls, logging configuration, redaction, and workflow boundaries. ### Must deliver ```text ai/provider/uckk/version.php ai/provider/uckk/settings.php ai/provider/uckk/db/install.xml ai/provider/uckk/db/upgrade.php ai/provider/uckk/db/access.php ai/provider/uckk/classes/local/ ai/provider/uckk/classes/provider/ ai/provider/uckk/classes/privacy/provider.php ai/provider/uckk/classes/task/ ai/provider/uckk/lang/en/aiprovider_uckk.php ai/provider/uckk/lang/fr/aiprovider_uckk.php ai/provider/uckk/tests/ ai/provider/uckk/tests/behat/ ai/provider/uckk/README.md ``` ### Actions ```text summarise_course_material map_problem extract_uncertainties draft_reflection summarise_assembly critique_ai_output prepare_integrity_review ``` ### Constraints * Every AI output is labeled as non-authoritative. * Prompts and responses can be logged according to site settings. * Sensitive workflows can disable AI. * AI cannot grade, sanction, validate integrity, publish final decisions, award badges, validate archive records, resolve disputes, compute Smart Vote readings, or reinterpret Konnaxion results as decisions. * Logged prompt/response records must be exportable and deletable according to Moodle privacy rules where they contain personal data. ### Required classes ```text aiprovider_uckk\local\client aiprovider_uckk\local\redactor aiprovider_uckk\local\logger aiprovider_uckk\local\policy aiprovider_uckk\provider\* aiprovider_uckk\task\cleanup_logs aiprovider_uckk\privacy\provider ``` ### Required tests ```text PHPUnit: provider enable/disable, redaction, logging policy, action authorization, privacy provider. Behat: governed AI labels, disabled sensitive workflow, restricted log access. ``` ## 12. Cross-plugin dependency contract The canonical dependency direction is: ```text local_uckk -> shared registry and component map in standalone-core mode -> optional Konnaxion bridge, Konnaxion mapping services, and sync logs in connected mode theme_uckk -> presentation only, may depend on local_uckk format_uckk -> course structure, may reference local_uckk and mod_uckkarchive mod_uckkchallenge -> challenge workflow, may call local_uckk, mod_uckkarchive, tool_uckkintegrity mod_uckkassembly -> assembly workflow in standalone-core mode; optional Smart Vote workflow in connected mode; may call local_uckk Konnaxion services only when enabled, plus mod_uckkarchive and tool_uckkintegrity mod_uckkarchive -> archive source of truth; preserves ordinary provenance packages in standalone mode and Smart Vote snapshots only in connected mode; may call local_uckk tool_uckkintegrity -> integrity workflow, may call local_uckk, archive, challenge, assembly tool_uckkseed -> installation/seeding orchestrator, may call all UCKK plugins through stable APIs block_uckk_dashboard -> display aggregator, may read from source plugins after capability checks report_uckk -> report aggregator; may read Smart Vote and Konnaxion-derived Moodle-side snapshots from source plugins after capability checks only in connected mode aiprovider_uckk -> governed AI bridge, may call local_uckk for policy/context but cannot own workflow authority ``` No plugin may create circular ownership of source records. Reading across plugins must go through stable helper/service APIs, not direct assumptions about another plugin's internal tables, unless explicitly documented and tested. When connected mode is enabled, Konnaxion integration must follow this direction: ```text Konnaxion external source family -> local_uckk Konnaxion bridge -> mod_uckkassembly Smart Vote workflow -> mod_uckkarchive provenance/archive preservation -> report_uckk reports and exports ``` Konnaxion never writes directly into Moodle source tables. Konnaxion identifiers never grant Moodle authority. Smart Vote readings never publish final Assembly decisions. ## 13. Implementation correction gates Before installing in Moodle, the codebase must pass these preflight gates: ```text [ ] No PHP code appears in amd/src/*.js. [ ] No JavaScript-only module appears in a .php controller file. [ ] No Markdown fences appear in .php files. [ ] Every .php file parses with php -l. [ ] Every version.php component matches its plugin path. [ ] Every declared service in db/services.php has a matching classes/external class. [ ] Every event referenced or emitted has a matching classes/event class. [ ] Every observer callback points to an existing class or function. [ ] Every scheduled task in db/tasks.php has a matching classes/task class. [ ] Every form reference has a matching classes/form class or Moodle form file. [ ] Every plugin storing personal data has classes/privacy/provider.php. [ ] Every install.xml validates as XMLDB. [ ] Every JSON preset validates as JSON. [ ] Every canonical variable from section 0.7 is resolved consistently across declarations, services, events, capabilities, tests, and presets. [ ] In connected mode, every Konnaxion table, capability, service, event, and status enum uses the canonical variable name and value. [ ] In connected mode, every Smart Vote workflow keeps computed readings separate from human/institutional decisions. [ ] In standalone-core mode, ordinary Assembly, Archive, Integrity, Report, and Seed workflows pass without Konnaxion credentials, endpoints, mappings, or Smart Vote snapshots. [ ] Every AMD module builds through Moodle's Grunt pipeline. ``` After preflight, the codebase must pass these Moodle gates: ```text [ ] Installs into a clean disposable Moodle site. [ ] admin/cli/upgrade.php --non-interactive passes. [ ] Caches purge without warnings. [ ] PHPUnit initializes and plugin tests pass. [ ] Behat initializes and major workflow features pass. [ ] Privacy API checks pass for every plugin storing or exposing personal data. [ ] Backup/restore checks pass for activity modules. [ ] Seed dry-run passes. [ ] Seed run creates a complete campus. [ ] Seed rerun is idempotent. [ ] Standalone-core workflows pass with Konnaxion disabled. [ ] In connected mode, Konnaxion timeout, failure, retry, disabled-state, and idempotency tests pass. [ ] In connected mode, Smart Vote request, import, review, contestation, archive, report, privacy export, and redaction tests pass. ``` ## 14. Plugin completion checklist Every plugin must pass: ```text [ ] Installs cleanly. [ ] Upgrades cleanly. [ ] Has a correct version.php component declaration. [ ] Has dependency declarations where needed. [ ] Has component strings in English and French. [ ] Has required capabilities in db/access.php. [ ] Uses canonical capability variables from section 0.7 when touching Konnaxion or Smart Vote in connected mode. [ ] Uses Moodle context checks on every page and service. [ ] Emits events for important actions. [ ] Uses canonical event variables from section 0.7 when touching Konnaxion or Smart Vote in connected mode. [ ] Has matching classes for every service, form, event, observer, task, output object, and privacy provider it declares. [ ] Has privacy provider when storing or exposing personal data. [ ] In connected mode, covers Konnaxion mappings, external identifiers, Smart Vote snapshots, expertise weights, contestations, and reports when stored or exposed. [ ] Has PHPUnit tests for services and business rules. [ ] Has Behat tests for major user workflows. [ ] Has AMD JavaScript that builds cleanly where browser behavior exists. [ ] Has install.xml and upgrade.php coverage for all owned tables. [ ] Uses canonical table variables from section 0.7 for Konnaxion and Smart Vote storage when connected-mode storage is enabled. [ ] Has backup/restore coverage when it is an activity module. [ ] Has README with purpose, install path, dependencies, admin settings, capabilities, data ownership, and test command. ``` ## 15. Standalone and connected-mode completion gates ### 15.1 Core standalone completion gate The plugin suite is complete in standalone-core mode only when: ```text [ ] All core plugins install cleanly with Konnaxion disabled. [ ] Core pages, services, events, tasks, forms, outputs, privacy providers, and tests resolve without Konnaxion credentials or endpoints. [ ] Assemblies support motions, ordinary votes/readings, decisions, minutes, contestations, and archive export without Smart Vote. [ ] Archives preserve Assembly decisions, challenge evidence, provenance, versions, and integrity records without Smart Vote snapshots. [ ] Reports render institutional UCKK records without Smart Vote or Konnaxion data. [ ] Seed creates the UCKK campus without active Konnaxion mappings. [ ] Dashboard, course format, challenge, archive, integrity, report, and AI workflows fail closed or hide Konnaxion/Smart Vote panels when connected mode is disabled. ``` ### 15.2 Optional Konnaxion-connected completion gate The connected profile is complete only when: ```text [ ] Konnaxion bridge settings are disabled by default and can be enabled by authorized administrators. [ ] Konnaxion mappings, sync logs, services, events, tasks, privacy providers, and tests use the canonical variables in section 0.7. [ ] Smart Vote readings can be requested, imported, reviewed, contested, archived, reported, exported, and redacted with Moodle capability checks. [ ] Smart Vote readings remain separate from human/institutional Assembly decisions. [ ] Konnaxion failures, timeouts, retries, disabled state, and idempotency are tested. [ ] Connected-mode features never become hard dependencies for the standalone-core gate. ``` ## 16. Non-negotiable authority boundaries ```text Theme presents; it does not decide. Course format structures; it does not own workflow records. Dashboard displays; it does not mutate source records. Reports aggregate; they do not become source of truth. Konnaxion computes Smart Vote readings; it does not own Moodle decisions. Smart Vote informs Assemblées; it does not decide. Seed creates and updates declared objects; it does not silently overwrite hand-edited records. Archive preserves provenance; it does not invent legitimacy. Assembly decides through Moodle-side human/institutional workflow; it does not surrender authority to external readings. Integrity reviews; it does not become unrestricted administration. AI assists; it never becomes final authority. ``` --- ## Update note This version aligns `DOC_03` with the shared UCKK-Moodle operating-mode rule: standalone-core mode is complete without Konnaxion, while Konnaxion/Smart Vote features are optional connected-mode obligations. ================================================================================================ FILE: docs/04_data_model_and_storage.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: b40f484787580f345a3d49e9264ef09960f31f3d11c3f3694244d4d7f44f080e CONTENT_BYTES: 48380 ================================================================================================ # 04 — Data Model and Storage **Status:** Final data design + standalone/connected-mode implementation correction contract **Purpose:** Define the cross-plugin UCKK-Moodle data model, including the standalone core storage contract and the optional Konnaxion-connected storage contract that enables Smart Vote readings without making Konnaxion a core dependency. This document is normative. A generated plugin file is not considered complete merely because it declares a table name, service, form, event, scheduled task, or privacy string. Every stored object must have a table owner, Moodle context, capability model, privacy handling, install/upgrade path, tests, and a documented state machine when it has workflow status. UCKK-Moodle is self-standing. Konnaxion is an optional connected-mode integration. When Konnaxion is disabled or unavailable, UCKK-Moodle must still install, seed, teach, deliberate, archive, report, and enforce permissions through Moodle-owned data. ## 0. Operating-mode storage boundary UCKK-Moodle has two storage profiles: | Profile | Meaning | Storage rule | |---|---|---| | `standalone_core` | UCKK-Moodle without Konnaxion | All core UCKK tables, file areas, privacy providers, state machines, reports, and tests must work without Konnaxion records. | | `connected_konnaxion` | UCKK-Moodle connected to Konnaxion | Adds Konnaxion mapping tables, sync logs, Smart Vote target mapping, Smart Vote snapshots, and Smart Vote audit records. | Canonical storage rules: ```text KONNAXION_REQUIRED_FOR_CORE = false SMART_VOTE_REQUIRED_FOR_CORE = false KONNAXION_DEFAULT_STATE = disabled SMART_VOTE_DEFAULT_STATE = disabled unless Konnaxion bridge is enabled DIRECT_WRITE_RULE = external_systems_never_write_moodle_source_tables PERMISSION_RULE = moodle_capabilities_remain_authoritative SMART_VOTE_AUTHORITY = computed_reading_only ``` Standalone mode must treat the absence of Konnaxion mappings, Smart Vote targets, Smart Vote snapshots, and Konnaxion sync logs as valid. An empty connected-mode table is not a missing institutional record. Connected mode may store imported or referenced Konnaxion data only through Moodle-owned tables, services, privacy providers, archive rules, and audit events. Konnaxion must never write directly into Moodle source tables. ## 1. Common storage principles All UCKK tables must use Moodle-compatible XMLDB definitions and Moodle upgrade paths. Initial schema belongs in each owning plugin's `db/install.xml`. Schema evolution belongs in that same plugin's `db/upgrade.php`. Runtime code, rendering code, service calls, validation workflows, archive export, privacy deletion, and seed execution must not be placed in `db/upgrade.php`. Stable fields must be first-class columns. `metadata` may store JSON only when the field is genuinely variable, extension-oriented, or non-query-critical. A value that is filtered, joined, permission-checked, sorted, reported, exported for privacy, or used in a state transition must be a real column. Common columns for UCKK-owned object tables: ```text id BIGINT PK courseid BIGINT NULL cmid BIGINT NULL contextid BIGINT NOT NULL userid BIGINT NULL createdby BIGINT NOT NULL modifiedby BIGINT NULL timecreated BIGINT NOT NULL timemodified BIGINT NOT NULL status VARCHAR(64) NOT NULL visibility VARCHAR(64) NOT NULL versionno BIGINT NOT NULL DEFAULT 1 provenancehash VARCHAR(128) NULL metadata LONGTEXT NULL ``` Implementation notes: - Moodle activity instance tables use Moodle's expected activity-module field conventions, including `course`, `name`, `intro`, `introformat`, `timecreated`, and `timemodified` where applicable. - Subordinate UCKK records should use `courseid`, `cmid`, and `contextid` when the object can be addressed outside the activity instance row. - Every foreign-key-like column must be indexed, even when Moodle XMLDB does not enforce a physical FK on all supported databases. - Every `userid`, `createdby`, `modifiedby`, `openedby`, `assignedto`, `proposerid`, `changedby`, and `owneruserid` field is personal-data-bearing and must be covered by the owning plugin's privacy provider. - Every table containing long text authored by a user must define privacy export, deletion/anonymisation, and retention behavior. - Every `status` and `visibility` column must have an allowed-value list in this document and tests for invalid transitions. ## 2. Implementation correction rules The current implementation pass must be corrected against these rules before install testing: ```text [ ] Every table listed here exists in exactly one owning plugin's db/install.xml. [ ] Every table has a future-safe db/upgrade.php path in the same plugin. [ ] Every table has a privacy-provider entry, or a documented null-provider reason. [ ] Every table with user data has PHPUnit coverage for create/read/update/delete/privacy export. [ ] Every status field has a documented state machine and transition guard. [ ] Every visibility field has a documented access rule and context check. [ ] Every file area has a pluginfile handler and capability check. [ ] Every external service that reads/writes table data has a matching classes/external/* implementation. [ ] Every event named in db/events.php or emitted by write code has a matching classes/event/* implementation. [ ] Every scheduled task named in db/tasks.php has a matching classes/task/* implementation. [ ] No page, service, task, upgrade step, or seed action references a table or class that does not exist. [ ] Standalone mode works when Konnaxion bridge and Smart Vote are disabled. [ ] Connected-mode Konnaxion tables use the canonical names in this document. [ ] Connected-mode Smart Vote records remain readings, not final Assembly decisions. ``` ## 3. Table ownership registry | Table | Owner plugin | Primary context | Personal data | Privacy action | Required tests | |---|---|---|---|---|---| | `local_uckk_program` | `local_uckk` | System/category | No direct user data | Metadata export only if user annotations are added | PHPUnit registry tests | | `local_uckk_pathway` | `local_uckk` | Category/user | May reference user assignment indirectly | Export assigned pathway records | PHPUnit pathway tests | | `local_uckk_player_profile` | `local_uckk` | User | Yes | Export/delete/anonymise by user | PHPUnit privacy + profile tests | | `local_uckk_provenance` | `local_uckk` | Source object context | May reference users and authored text | Export by user where linked; retain institutional provenance when legally required | PHPUnit provenance tests | | `local_uckk_kx_user_map` | `local_uckk` | User/system | Yes, identity-linking data | Export/delete/anonymise according to user privacy policy; never expose secrets | PHPUnit connected-mode privacy + mapping tests | | `local_uckk_kx_object_map` | `local_uckk` | Source object context | Usually no direct user data, may become personal by linkage | Export where linked to a user; retain/invalidate with mapped object | PHPUnit mapping + provenance tests | | `local_uckk_kx_sync_log` | `local_uckk` | System/source object context | May contain admin user ids and endpoint metadata | Retain according to Konnaxion retention setting; redact payloads and secrets | PHPUnit sync log + retention tests | | `uckkchallenge` | `mod_uckkchallenge` | Module | Limited author/config data | Export module participation metadata | PHPUnit module tests | | `uckkchallenge_submission` | `mod_uckkchallenge` | Module | Yes | Export/delete/anonymise submissions and links | PHPUnit + Behat submission tests | | `uckkassembly` | `mod_uckkassembly` | Module | Limited author/config data | Export participation metadata | PHPUnit module tests | | `uckkassembly_motion` | `mod_uckkassembly` | Module | Yes | Export/delete/anonymise authored motions where policy allows | PHPUnit motion tests | | `uckkassembly_decision` | `mod_uckkassembly` | Module | May contain user references | Export where user contributed; retain institutional decision record | PHPUnit decision tests | | `uckkassembly_kx_vote_target` | `mod_uckkassembly` | Module | May reference participants or mapped objects | Export where user-linked; archive/invalidate with Assembly object | PHPUnit Smart Vote target + capability tests | | `uckkassembly_sv_snapshot` | `mod_uckkassembly` | Module | May contain aggregated or linkable voting data | Export/redact according to visibility and source privacy; retain when used in decisions | PHPUnit Smart Vote snapshot + privacy tests | | `uckkassembly_sv_result_audit` | `mod_uckkassembly` | Module/integrity context | Yes, may reference reviewers and contesters | Export/restrict/retain under integrity and Assembly retention rules | PHPUnit Smart Vote audit + contestation tests | | `uckkarchive` | `mod_uckkarchive` | Module | Limited config data | Export archive participation metadata | PHPUnit module tests | | `uckkarchive_item` | `mod_uckkarchive` | Module/course/user | Yes | Export/delete/anonymise according to visibility and retention | PHPUnit archive tests | | `uckkarchive_version` | `mod_uckkarchive` | Parent archive item | Yes | Export versions where user-authored; retention rules apply | PHPUnit versioning tests | | `tool_uckkintegrity_case` | `tool_uckkintegrity` | System/course/module/user | Yes, sensitive | Restricted export; deletion/anonymisation controlled by case retention | PHPUnit privacy + case tests | | `tool_uckkintegrity_note` | `tool_uckkintegrity` | Parent integrity case | Yes, sensitive | Restricted export; deletion/anonymisation controlled by case retention | PHPUnit note tests | | `tool_uckkseed_log` | `tool_uckkseed` | System | Admin user ids and logs | Export/delete old logs by retention | PHPUnit seed log tests | | `aiprovider_uckk_log` | `aiprovider_uckk` | Originating action context | Yes, sensitive | Export/delete prompt/response logs; redact when configured | PHPUnit AI privacy tests | Plugins with no own tables must say so explicitly in their privacy provider and tests: | Plugin | Expected storage posture | |---|---| | `theme_uckk` | Presentation-only; no own tables. Settings are Moodle config. | | `format_uckk` | Prefer Moodle `course_format_options`; no own tables unless later justified. | | `block_uckk_dashboard` | Prefer block config and read-only aggregation; user preferences need an explicit table and privacy provider. | | `report_uckk` | Read-only reports; no own tables unless caching is introduced. Cached personal data requires privacy coverage. | ## 4. Context strategy | Object | Moodle context | Required access rule | |---|---|---| | Program registry | System or category context | View/manage through `local/uckk:*` capabilities. | | Pathway assignment | User + category context | User can view own assignment; managers view within category/system scope. | | Course format data | Course context | Course capability checks only; no hidden learner data in diagnostics. | | Challenge instance | Module context | Module view/manage capabilities. | | Challenge submission | Module context | Submitter, mentor, grader, or manager according to capability. | | Assembly instance | Module context | Module participation/view/manage capabilities. | | Motion / vote / decision | Module context | Participant visibility plus decision archive rules. | | Archive item | Module, course, or user context depending on owner | Visibility and provenance determine access. | | Integrity case | System, course, module, or user context | Restricted Inquisiteur capabilities; no broad manager leakage by default. | | Dashboard preference | User context | User owns own preference; managers do not need write access. | | AI prompt/response logs | Context of originating action | Only authorised log viewers; never exposed to normal learners by default. | | Konnaxion user mapping | User + system context | User privacy controls plus `local/uckk:managekonnaxion` or equivalent mapped capability. | | Konnaxion object mapping | Context of mapped Moodle object | Same visibility as mapped object plus Konnaxion mapping capability. | | Konnaxion sync log | System + mapped object context when available | Restricted operational visibility; payloads disabled/redacted by default. | | Smart Vote target | Assembly module context | Assembly capability checks; hidden when Konnaxion-connected mode is disabled. | | Smart Vote snapshot | Assembly module context | View only as a reading, never as a final decision; archive visibility applies when preserved. | | Smart Vote result audit | Assembly or integrity context | Restricted review/contestation permissions; never broad report visibility by default. | Context ids must be stored when they are needed for privacy export, capability checks, event payloads, report filtering, or file serving. If a context can be derived safely from `cmid` or `courseid`, the code may derive it, but tests must prove the derivation. ## 5. `local_uckk` tables ### `local_uckk_program` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | shortname | VARCHAR(100) | Stable program key | | fullname | VARCHAR(255) | Display name | | programtype | VARCHAR(64) | `tronc_commun`, `baccalaureat`, `mineure`, `lab`, `seminar` | | categoryid | BIGINT | Linked Moodle category | | description | LONGTEXT | Canonical description | | status | VARCHAR(64) | `draft`, `active`, `hidden`, `archived` | | sortorder | BIGINT | Display order | Implementation contract: ```text Owner: local_uckk Install path: local/uckk/db/install.xml Upgrade path: local/uckk/db/upgrade.php Classes required: local_uckk\local\program_repository, local_uckk\external\get_programs Events: local_uckk\event\program_created, local_uckk\event\program_updated Privacy: no direct user data unless user-authored descriptions are later added Tests: repository, external service, seed idempotency ``` ### `local_uckk_pathway` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | programid | BIGINT | Program FK | | shortname | VARCHAR(100) | Pathway key | | fullname | VARCHAR(255) | Display name | | requiredcourseids | LONGTEXT | JSON list | | requiredbadges | LONGTEXT | JSON list | | requiredcompetencies | LONGTEXT | JSON list | | status | VARCHAR(64) | `draft`, `active`, `archived` | Implementation contract: ```text Owner: local_uckk Install path: local/uckk/db/install.xml Upgrade path: local/uckk/db/upgrade.php Classes required: local_uckk\local\pathway_repository, local_uckk\external\get_pathways Events: local_uckk\event\pathway_created, local_uckk\event\pathway_updated Privacy: pathway definitions are not personal; assignments are personal if stored separately Tests: repository, JSON validation, seed idempotency ``` ### `local_uckk_player_profile` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | userid | BIGINT | Moodle user | | displaytitle | VARCHAR(255) | Public UCKK title | | symbolicroles | LONGTEXT | JSON list | | activepathwayids | LONGTEXT | JSON list | | portfolioarchiveid | BIGINT NULL | Archive link | | integrityflags | LONGTEXT NULL | JSON | | visibility | VARCHAR(64) | `private`, `cohort`, `course`, `public` | Implementation contract: ```text Owner: local_uckk Install path: local/uckk/db/install.xml Upgrade path: local/uckk/db/upgrade.php Classes required: local_uckk\local\profile_repository, local_uckk\external\get_profile, local_uckk\external\update_profile Events: local_uckk\event\profile_updated Privacy: full export/delete/anonymise by userid Tests: repository, permission checks, privacy provider, Behat profile view/edit workflow ``` ### `local_uckk_provenance` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | component | VARCHAR(100) | Owning plugin | | itemtype | VARCHAR(100) | Object type | | itemid | BIGINT | Object id | | contextid | BIGINT | Context of the target object | | sourcecomponent | VARCHAR(100) | Origin | | sourceid | BIGINT NULL | Origin id | | sourcetext | LONGTEXT NULL | Human source description | | hash | VARCHAR(128) NULL | Integrity hash | | state | VARCHAR(64) | `draft`, `verified`, `contested`, `invalidated` | | createdby | BIGINT | User who created the provenance record | | timecreated | BIGINT | Creation time | Implementation contract: ```text Owner: local_uckk unless a plugin keeps provenance locally Install path: local/uckk/db/install.xml Upgrade path: local/uckk/db/upgrade.php Classes required: local_uckk\local\provenance_repository Events: local_uckk\event\provenance_created, local_uckk\event\provenance_state_changed Privacy: export records created by or directly referencing a user; retain institutional hashes when needed Tests: hash stability, state transition, privacy export ``` ## 6. Optional Konnaxion-connected storage This section is active only for `connected_konnaxion` mode. These tables are not required for standalone UCKK-Moodle behavior, but if the Konnaxion bridge is enabled they become part of the connected-mode acceptance gate. The abbreviation `kx` is allowed only in table and internal variable names. User-facing documentation and UI must use `Konnaxion`. ### `local_uckk_kx_user_map` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | userid | BIGINT | Moodle user id | | externalid | VARCHAR(255) | Konnaxion user identifier | | externaltype | VARCHAR(100) | Konnaxion object type, normally `User` or equivalent identity type | | sourceversion | VARCHAR(255) NULL | External source version/revision/timestamp where available | | syncstatus | VARCHAR(64) | `queued`, `running`, `succeeded`, `failed`, `retry_waiting`, `skipped`, `disabled` | | mappingstatus | VARCHAR(64) | `draft`, `active`, `suspended`, `superseded`, `archived`, `invalidated` | | provenancehash | VARCHAR(128) NULL | Integrity hash for mapping provenance | | createdby | BIGINT | User who created or approved mapping | | timecreated | BIGINT | Created time | | timemodified | BIGINT | Modified time | Implementation contract: ```text Owner: local_uckk Install path: local/uckk/db/install.xml Upgrade path: local/uckk/db/upgrade.php Classes required in connected mode: local_uckk\service\konnaxion_mapping_service, local_uckk\external\create_konnaxion_mapping, local_uckk\external\get_konnaxion_mapping Events: local_uckk\event\konnaxion_mapping_created Privacy: identity-linking data; export/delete/anonymise by userid where policy allows; never store API secrets Tests: connected-mode mapping CRUD, privacy provider, capability checks, disabled-mode behavior ``` ### `local_uckk_kx_object_map` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | component | VARCHAR(100) | Moodle component owning the mapped object | | itemtype | VARCHAR(100) | Moodle-side object type | | itemid | BIGINT | Moodle-side object id | | contextid | BIGINT | Context of the mapped object | | externalid | VARCHAR(255) | Konnaxion object identifier | | externaltype | VARCHAR(100) | Konnaxion object type such as `Vote`, `VoteModality`, `VoteResult`, or `IntegrationMapping` | | sourceversion | VARCHAR(255) NULL | External source version/revision/timestamp where available | | mappingstatus | VARCHAR(64) | `draft`, `active`, `suspended`, `superseded`, `archived`, `invalidated` | | provenancehash | VARCHAR(128) NULL | Integrity hash for mapping provenance | | createdby | BIGINT | User who created mapping | | timecreated | BIGINT | Created time | | timemodified | BIGINT | Modified time | Implementation contract: ```text Owner: local_uckk Install path: local/uckk/db/install.xml Upgrade path: local/uckk/db/upgrade.php Classes required in connected mode: local_uckk\service\konnaxion_mapping_service Events: local_uckk\event\konnaxion_mapping_created Privacy: export if user-linked; retain/invalidate according to mapped Moodle object lifecycle Tests: mapping uniqueness, context checks, invalidation, privacy metadata ``` ### `local_uckk_kx_sync_log` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | component | VARCHAR(100) | Moodle component initiating sync | | itemtype | VARCHAR(100) NULL | Moodle-side object type | | itemid | BIGINT NULL | Moodle-side object id | | contextid | BIGINT NULL | Context when available | | operation | VARCHAR(100) | `healthcheck`, `map`, `sync`, `request_reading`, `import_snapshot`, `retry` | | syncstatus | VARCHAR(64) | `queued`, `running`, `succeeded`, `failed`, `retry_waiting`, `skipped`, `disabled` | | endpoint | VARCHAR(255) NULL | Endpoint label or path, never full secret-bearing URL | | statuscode | BIGINT NULL | Remote status code when available | | idempotencykey | VARCHAR(128) NULL | Retry/idempotency key | | errormessage | LONGTEXT NULL | Redacted error summary | | metadata | LONGTEXT NULL | Redacted JSON metadata; payload logging disabled by default | | createdby | BIGINT NULL | User or task actor where applicable | | timecreated | BIGINT | Created time | Implementation contract: ```text Owner: local_uckk Install path: local/uckk/db/install.xml Upgrade path: local/uckk/db/upgrade.php Classes required in connected mode: local_uckk\service\konnaxion_sync_service, local_uckk\external\sync_konnaxion Events: local_uckk\event\konnaxion_sync_completed Privacy: restricted operational log; secrets and raw payloads forbidden by default; retention cleanup required Tests: timeout, retry, disabled state, idempotency, retention cleanup, secret redaction ``` ### `uckkassembly_kx_vote_target` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | assemblyid | BIGINT | FK to `uckkassembly.id` | | motionid | BIGINT NULL | FK to `uckkassembly_motion.id` when target is motion-specific | | contextid | BIGINT | Assembly module context | | externalid | VARCHAR(255) | Konnaxion vote target identifier | | externaltype | VARCHAR(100) | Usually `Vote` or `IntegrationMapping` | | targetstatus | VARCHAR(64) | `draft`, `mapped`, `active`, `closed`, `archived`, `contested` | | readingmethod | VARCHAR(100) NULL | Smart Vote modality or weighting method | | sourceversion | VARCHAR(255) NULL | External source version/revision/timestamp where available | | provenancehash | VARCHAR(128) NULL | Mapping or request hash | | createdby | BIGINT | User who requested or approved target | | timecreated | BIGINT | Created time | | timemodified | BIGINT | Modified time | Implementation contract: ```text Owner: mod_uckkassembly Install path: mod/uckkassembly/db/install.xml Upgrade path: mod/uckkassembly/db/upgrade.php Classes required in connected mode: mod_uckkassembly\external\request_smart_vote_reading Events: mod_uckkassembly\event\smart_vote_reading_requested Privacy: export if linked to user-created motion or request; retain with Assembly decision when used Tests: target mapping, capability checks, disabled-mode hiding, state transitions ``` ### `uckkassembly_sv_snapshot` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | assemblyid | BIGINT | FK to `uckkassembly.id` | | motionid | BIGINT NULL | FK to `uckkassembly_motion.id` | | targetid | BIGINT | FK to `uckkassembly_kx_vote_target.id` | | contextid | BIGINT | Assembly module context | | raw_data | LONGTEXT NULL | Imported or referenced source facts before interpretation; store aggregated/redacted form where possible | | reading_method | VARCHAR(100) | Declared modality, weighting, or algorithmic reading rule | | computed_reading | LONGTEXT | Non-sovereign Smart Vote output | | expertise_weight | LONGTEXT NULL | Weighting metadata; sensitive when linkable to users | | minority_report | LONGTEXT NULL | Dissenting or alternative interpretation if supplied | | integrity_warning | LONGTEXT NULL | Warning that may open integrity review but is not itself a sanction | | contestation_status | VARCHAR(64) | `imported`, `under_review`, `accepted_as_reading`, `contested`, `superseded`, `archived`, `invalidated` | | archiveitemid | BIGINT NULL | Archive item preserving snapshot when archived | | provenancehash | VARCHAR(128) NULL | Snapshot integrity hash | | importedby | BIGINT | User or task actor that imported snapshot | | timecreated | BIGINT | Created time | Implementation contract: ```text Owner: mod_uckkassembly Install path: mod/uckkassembly/db/install.xml Upgrade path: mod/uckkassembly/db/upgrade.php Classes required in connected mode: mod_uckkassembly\external\import_smart_vote_snapshot Events: mod_uckkassembly\event\smart_vote_snapshot_imported, mod_uckkassembly\event\smart_vote_snapshot_archived Privacy: classify raw/weighted data before display/export; retain institutional snapshot when used in decision, with redaction rules Tests: import validation, no overwrite without audit trail, privacy export/redaction, archive linkage ``` ### `uckkassembly_sv_result_audit` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | snapshotid | BIGINT | FK to `uckkassembly_sv_snapshot.id` | | contextid | BIGINT | Assembly or integrity context | | auditstatus | VARCHAR(64) | `recorded`, `reviewed`, `corrected`, `contested`, `resolved` | | action | VARCHAR(100) | Review, correction, contestation, supersession, archive, or invalidation action | | note | LONGTEXT NULL | Audit note or correction reason | | changedby | BIGINT | User who performed action | | supersedessnapshotid | BIGINT NULL | Earlier snapshot superseded by this action | | archiveitemid | BIGINT NULL | Archive item preserving the audit record | | timecreated | BIGINT | Created time | Implementation contract: ```text Owner: mod_uckkassembly Install path: mod/uckkassembly/db/install.xml Upgrade path: mod/uckkassembly/db/upgrade.php Classes required in connected mode: mod_uckkassembly\external\contest_smart_vote_snapshot Events: mod_uckkassembly\event\smart_vote_snapshot_contested Privacy: restricted audit trail; export user-authored contestations where policy allows; retain institutional audit history Tests: review, correction, contestation, supersession, archive linkage, restricted visibility ``` Smart Vote data remains `computed_reading_only`. The human/institutional Assembly decision remains in `uckkassembly_decision`; Smart Vote snapshots must not overwrite that table or publish decisions automatically. ## 7. `mod_uckkchallenge` tables ### `uckkchallenge` | Field | Type | Purpose | |---|---|---| | id | BIGINT | Instance id | | course | BIGINT | Moodle course id | | name | VARCHAR(255) | Activity name | | intro | LONGTEXT | Moodle intro | | introformat | SMALLINT | Moodle intro format | | challengecode | VARCHAR(100) | Stable challenge code | | challengetype | VARCHAR(64) | `public`, `internal`, `evaluated`, `lab` | | statement | LONGTEXT | Challenge statement | | rules | LONGTEXT | Rules | | criteria | LONGTEXT | Evaluation criteria | | evidencepolicy | LONGTEXT | Expected proof | | corridors | LONGTEXT | JSON corridors | | integrityrequired | TINYINT | Requires Inquisiteur review | | archivepolicy | VARCHAR(64) | `none`, `summary`, `full` | | timeopen | BIGINT | Open time | | timeclose | BIGINT | Close time | | status | VARCHAR(64) | `draft`, `open`, `closed`, `archived` | | timecreated | BIGINT | Creation time | | timemodified | BIGINT | Modified time | ### `uckkchallenge_submission` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | challengeid | BIGINT | FK to `uckkchallenge.id` | | userid | BIGINT | Submitter | | groupid | BIGINT NULL | Team | | title | VARCHAR(255) | Submission title | | body | LONGTEXT | Submission text | | proofsummary | LONGTEXT | Evidence summary | | status | VARCHAR(64) | `draft`, `submitted`, `review`, `revision`, `validated`, `archived` | | grade | DECIMAL NULL | Grade if used | | mentorfeedback | LONGTEXT NULL | Feedback | | integritycaseid | BIGINT NULL | Integrity case | | archiveitemid | BIGINT NULL | Archive link | | timecreated | BIGINT | Created time | | timemodified | BIGINT | Modified time | Implementation contract: ```text Owner: mod_uckkchallenge Install path: mod/uckkchallenge/db/install.xml Upgrade path: mod/uckkchallenge/db/upgrade.php Classes required: mod_uckkchallenge\external\*, mod_uckkchallenge\event\*, mod_uckkchallenge\privacy\provider Events: challenge_viewed, submission_created, submission_updated, submission_validated, submission_archived Privacy: export/delete/anonymise submissions, feedback, files, and user references Tests: lib callbacks, repository/service methods, privacy provider, Behat submission workflow ``` ## 8. `mod_uckkassembly` tables ### `uckkassembly` | Field | Type | Purpose | |---|---|---| | id | BIGINT | Instance id | | course | BIGINT | Course id | | name | VARCHAR(255) | Assembly name | | intro | LONGTEXT | Moodle intro | | introformat | SMALLINT | Moodle intro format | | assemblytype | VARCHAR(64) | `savoirs`, `defis`, `joueurs`, `batisseurs`, `inquisiteurs`, `grand_jeu` | | scope | VARCHAR(64) | `course`, `cohort`, `program`, `public` | | rules | LONGTEXT | Procedure | | decisionmethod | VARCHAR(64) | `consensus`, `vote`, `smart_reading`, `mentor_decision` | | status | VARCHAR(64) | `planned`, `open`, `deliberation`, `decision`, `archived` | | timecreated | BIGINT | Created time | | timemodified | BIGINT | Modified time | ### `uckkassembly_motion` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | assemblyid | BIGINT | FK | | proposerid | BIGINT | User | | title | VARCHAR(255) | Motion title | | body | LONGTEXT | Motion | | status | VARCHAR(64) | `submitted`, `accepted`, `amended`, `rejected`, `decided` | | decisionid | BIGINT NULL | FK | | timecreated | BIGINT | Created time | | timemodified | BIGINT | Modified time | ### `uckkassembly_decision` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | assemblyid | BIGINT | FK | | motionid | BIGINT | FK | | decisiontext | LONGTEXT | Decision | | reasoning | LONGTEXT | Rationale | | minorityreport | LONGTEXT NULL | Minority record | | contestableuntil | BIGINT NULL | Appeal window | | archiveitemid | BIGINT NULL | Archive link | | createdby | BIGINT | User who recorded decision | | timecreated | BIGINT | Created time | Implementation contract: ```text Owner: mod_uckkassembly Install path: mod/uckkassembly/db/install.xml Upgrade path: mod/uckkassembly/db/upgrade.php Classes required: mod_uckkassembly\external\*, mod_uckkassembly\event\*, mod_uckkassembly\privacy\provider Events: motion_submitted, motion_updated, vote_cast, decision_recorded, decision_archived Privacy: export/delete/anonymise participant content where policy allows; retain institutional decisions with attribution rules Tests: motion/decision services, state transitions, privacy provider, Behat assembly workflow ``` ## 9. `mod_uckkarchive` tables ### `uckkarchive` Standard Moodle module instance table. Required Moodle-style fields: ```text id course name intro introformat timecreated timemodified ``` Additional UCKK archive configuration fields may be added only when they are stable and reportable. Variable display settings belong in module config only if they are not used for access control, reporting, privacy export, or state transitions. ### `uckkarchive_item` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | archiveid | BIGINT | Module instance | | contextid | BIGINT | Access/privacy context | | itemtype | VARCHAR(64) | `proof`, `decision`, `kristal`, `portfolio_item`, `minutes` | | title | VARCHAR(255) | Title | | summary | LONGTEXT | Summary | | body | LONGTEXT | Content | | owneruserid | BIGINT NULL | User owner | | sourcecomponent | VARCHAR(100) | Origin | | sourceitemid | BIGINT NULL | Origin id | | validationstate | VARCHAR(64) | `draft`, `reviewed`, `validated`, `contested`, `invalidated` | | visibility | VARCHAR(64) | `private`, `cohort`, `course`, `public` | | provenancehash | VARCHAR(128) NULL | Integrity/provenance hash | | timecreated | BIGINT | Created time | | timemodified | BIGINT | Modified time | ### `uckkarchive_version` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | itemid | BIGINT | Archive item | | versionno | BIGINT | Version | | body | LONGTEXT | Snapshot | | changedby | BIGINT | User | | changereason | LONGTEXT | Reason | | timecreated | BIGINT | Created | Implementation contract: ```text Owner: mod_uckkarchive Install path: mod/uckkarchive/db/install.xml Upgrade path: mod/uckkarchive/db/upgrade.php Classes required: mod_uckkarchive\form\*, mod_uckkarchive\external\*, mod_uckkarchive\event\*, mod_uckkarchive\privacy\provider Events: archive_viewed, archive_item_created, archive_item_updated, archive_item_validated, archive_item_contested, archive_item_exported Privacy: export/delete/anonymise owned items, versions, files, and restricted evidence according to retention rules Tests: lib callbacks, file API, provenance, external services, privacy provider, Behat archive workflow ``` ## 10. `tool_uckkintegrity` tables ### `tool_uckkintegrity_case` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | casetype | VARCHAR(100) | Case type | | subjectcomponent | VARCHAR(100) | Related plugin | | subjectid | BIGINT | Related object | | contextid | BIGINT | Case context | | openedby | BIGINT | User | | assignedto | BIGINT NULL | Inquisiteur | | severity | VARCHAR(64) | `low`, `normal`, `high`, `critical` | | status | VARCHAR(64) | `opened`, `triaged`, `under_review`, `waiting_for_response`, `correction_required`, `resolved`, `dismissed`, `escalated`, `archived` | | summary | LONGTEXT | Summary | | decision | LONGTEXT NULL | Decision | | archiveitemid | BIGINT NULL | Archive link | | timecreated | BIGINT | Created time | | timemodified | BIGINT | Modified time | ### `tool_uckkintegrity_note` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | caseid | BIGINT | FK | | userid | BIGINT | Author | | notetype | VARCHAR(64) | `observation`, `evidence`, `response`, `decision` | | body | LONGTEXT | Note | | visibility | VARCHAR(64) | `restricted`, `parties`, `public_summary` | | timecreated | BIGINT | Created time | Implementation contract: ```text Owner: tool_uckkintegrity Install path: admin/tool/uckkintegrity/db/install.xml Upgrade path: admin/tool/uckkintegrity/db/upgrade.php Classes required: tool_uckkintegrity\form\*, tool_uckkintegrity\external\*, tool_uckkintegrity\event\*, tool_uckkintegrity\privacy\provider Events: case_opened, case_assigned, note_created, decision_recorded, case_closed Privacy: sensitive data; restricted export and deletion with retention controls Tests: case repository, capability checks, privacy provider, Behat case workflow ``` ## 11. `tool_uckkseed` tables ### `tool_uckkseed_log` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | userid | BIGINT | Admin/operator user | | action | VARCHAR(64) | `seed`, `reset`, `validate`, `export_preset` | | mode | VARCHAR(64) | `dryrun`, `execute` | | status | VARCHAR(64) | `started`, `completed`, `failed` | | summary | LONGTEXT | Human summary | | metadata | LONGTEXT NULL | JSON execution detail | | timecreated | BIGINT | Execution time | Implementation contract: ```text Owner: tool_uckkseed Install path: admin/tool/uckkseed/db/install.xml Upgrade path: admin/tool/uckkseed/db/upgrade.php Classes required: tool_uckkseed\local\*, tool_uckkseed\form\*, tool_uckkseed\privacy\provider Events: seed_started, seed_completed, seed_failed, reset_started, reset_completed, validation_completed Privacy: export/delete admin execution logs by userid and retention period Tests: idempotent seed, dry run, reset scoping, privacy provider ``` ## 12. `aiprovider_uckk` tables ### `aiprovider_uckk_log` | Field | Type | Purpose | |---|---|---| | id | BIGINT | PK | | userid | BIGINT | Requesting user | | contextid | BIGINT | Originating context | | actionname | VARCHAR(100) | AI action | | model | VARCHAR(100) | Provider model | | prompttext | LONGTEXT NULL | Prompt sent, if logging enabled | | responsetext | LONGTEXT NULL | Response stored, if logging enabled | | status | VARCHAR(64) | `requested`, `completed`, `failed`, `redacted`, `deleted` | | metadata | LONGTEXT NULL | JSON technical detail | | timecreated | BIGINT | Created time | Implementation contract: ```text Owner: aiprovider_uckk Install path: ai/provider/uckk/db/install.xml Upgrade path: ai/provider/uckk/db/upgrade.php Classes required: aiprovider_uckk\privacy\provider and provider/service classes required by Moodle AI integration Events: ai_request_created, ai_request_completed, ai_request_failed, ai_log_deleted Privacy: export/delete/redact prompts and responses by userid and retention settings Tests: provider behavior, redaction, retention cleanup, privacy provider ``` AI storage constraints: ```text [ ] AI output is never stored as final authority. [ ] AI logs must preserve originating contextid. [ ] Prompt and response logging must be configurable. [ ] Redaction settings must affect stored data, not only display output. [ ] Integrity, grading, validation, and sanction workflows cannot delegate final decisions to AI. ``` ## 13. File API areas | Component | File area | Purpose | Required access check | |---|---|---|---| | `mod_uckkchallenge` | `submission` | Challenge proof files | Submitter/mentor/grader/manager by module context | | `mod_uckkchallenge` | `feedback` | Mentor feedback attachments | Submitter and authorised reviewers only | | `mod_uckkassembly` | `motion` | Motion attachments | Assembly participant or manager by module context | | `mod_uckkassembly` | `minutes` | Minutes and decision files | Assembly visibility + decision publication state | | `mod_uckkassembly` | `smartvote_snapshot` | Optional connected-mode Smart Vote snapshot attachments or preserved source packages | Assembly Smart Vote visibility + archive/redaction rules | | `mod_uckkarchive` | `item` | Archive item files | Archive item visibility + provenance state | | `mod_uckkarchive` | `version` | Versioned snapshots | Same as parent item, with restricted invalidated/contested handling | | `mod_uckkarchive` | `smartvote_archive` | Optional archived Smart Vote reading packages | Archive visibility + provenance + contestation state | | `tool_uckkintegrity` | `case` | Restricted case evidence | Inquisiteur/restricted parties only | | `local_uckk` | `profile` | Optional profile artifacts | Owner or authorised viewer only | | `aiprovider_uckk` | none by default | AI logs are DB text, not files | Add file area only with privacy contract | File API contract: ```text [ ] Each file area has a *_pluginfile() handler or documented Moodle subsystem handler. [ ] Each handler validates context, itemid, filearea, capability, and visibility. [ ] Files linked to personal data are included in privacy export/delete. [ ] Tests cover allowed and denied access. ``` ## 14. State machines ### Generic visibility states ```text private -> cohort -> course -> public public -> course -> cohort -> private ``` Visibility changes must be logged by event when they affect access or publication. ### Archive validation states ```text draft -> reviewed -> validated draft -> reviewed -> contested validated -> contested -> reviewed -> validated contested -> invalidated ``` ### Challenge submission states ```text draft -> submitted -> review -> revision -> submitted review -> validated validated -> archived submitted -> archived ``` ### Assembly decision states ```text planned -> open -> deliberation -> decision -> archived ``` ### Integrity case states ```text opened -> triaged -> under_review -> waiting_for_response -> under_review under_review -> correction_required -> under_review under_review -> resolved -> archived under_review -> dismissed -> archived under_review -> escalated -> archived ``` ### Optional Konnaxion sync states ```text queued -> running -> succeeded queued -> running -> failed -> retry_waiting -> queued queued -> skipped queued -> disabled running -> failed failed -> retry_waiting ``` ### Optional Konnaxion mapping states ```text draft -> active active -> suspended -> active active -> superseded -> archived active -> invalidated suspended -> archived ``` ### Optional Smart Vote target states ```text draft -> mapped -> active -> closed -> archived active -> contested contested -> active contested -> archived ``` ### Optional Smart Vote snapshot states ```text imported -> under_review -> accepted_as_reading imported -> under_review -> contested accepted_as_reading -> archived accepted_as_reading -> superseded contested -> under_review contested -> invalidated ``` ### Optional Smart Vote audit states ```text recorded -> reviewed -> resolved recorded -> contested -> reviewed -> resolved reviewed -> corrected -> resolved ``` Every transition requires: ```text [ ] A capability check. [ ] A context check. [ ] A repository/service method. [ ] An event emission. [ ] A PHPUnit test. [ ] A Behat scenario when user-facing. ``` ## 15. Data integrity rules ```text [ ] Every archive item must have provenance. [ ] Every validated challenge must have at least one proof record or a documented no-file evidence policy. [ ] Every assembly decision must have a motion and decision record. [ ] Every integrity decision must have a case record and decision note. [ ] Every user-facing status must be stored, not inferred only from UI. [ ] Every important change must emit an event. [ ] Every personal-data table must be included in privacy export and deletion/anonymisation. [ ] Every foreign-key-like field must be indexed. [ ] Every cross-plugin reference must tolerate the target plugin being disabled or missing unless declared as a dependency. [ ] Every seed-created record must be idempotently identifiable by stable key. [ ] Standalone mode must tolerate empty or absent connected-mode records. [ ] Konnaxion must never write directly into Moodle source tables. [ ] Konnaxion mappings must preserve external identifiers without storing secrets. [ ] Smart Vote snapshots must distinguish raw data, reading method, computed reading, human/institutional decision reference, minority report, integrity warning, contestation status, and archive linkage. [ ] Smart Vote snapshots must not overwrite `uckkassembly_decision` or publish final decisions. ``` ## 16. Install and upgrade rules ```text [ ] db/install.xml creates only this plugin's own tables. [ ] db/install.xml validates with Moodle XMLDB tools. [ ] db/upgrade.php is self-contained and has no rendering, service calls, page setup, or workflow logic. [ ] Every schema change is guarded by table/field/index existence checks. [ ] Every upgrade step ends with upgrade_plugin_savepoint(). [ ] Data migrations are safe to re-run after partial failure. [ ] Fresh install and upgrade-from-previous-version both produce the same final schema. [ ] Connected-mode tables are created by their owning plugins only. [ ] Konnaxion bridge disabled state does not block install or upgrade. [ ] Empty connected-mode tables do not cause seed, report, privacy, or archive failures. ``` No plugin may create another plugin's tables. Cross-plugin data must be created through seed/repository APIs after all dependent plugins are installed. ## 17. Privacy and retention rules ```text [ ] Each plugin has classes/privacy/provider.php. [ ] Null providers are allowed only when the plugin truly stores no personal data. [ ] Every userid-like field is mapped in privacy metadata. [ ] Every authored LONGTEXT field is exported or explicitly retained/anonymised by policy. [ ] Every file area containing personal data participates in privacy export/delete. [ ] Integrity cases and archive records may use retention rules, but the rule must be explicit. [ ] AI logs must respect redaction and retention settings. [ ] Seed logs must have retention cleanup. [ ] Konnaxion identity mappings are identity-linking personal data and require privacy export/delete/anonymisation rules. [ ] Konnaxion object mappings require provenance and lifecycle retention rules. [ ] Konnaxion sync logs require redaction, secret exclusion, and retention cleanup. [ ] Smart Vote snapshots require privacy classification before display, export, report, archive, or AI use. [ ] Absence of a Smart Vote reading is valid standalone provenance, not a missing record. ``` Privacy providers required by storage: ```text local/uckk/classes/privacy/provider.php mod/uckkchallenge/classes/privacy/provider.php mod/uckkassembly/classes/privacy/provider.php mod/uckkarchive/classes/privacy/provider.php admin/tool/uckkintegrity/classes/privacy/provider.php admin/tool/uckkseed/classes/privacy/provider.php ai/provider/uckk/classes/privacy/provider.php ``` Privacy providers required to declare null/no-own-data posture when appropriate: ```text theme/uckk/classes/privacy/provider.php course/format/uckk/classes/privacy/provider.php blocks/uckk_dashboard/classes/privacy/provider.php report/uckk/classes/privacy/provider.php ``` If any of those later stores personal data, the null posture must be replaced by a full provider. ## 18. Definition of done The data layer has two acceptance gates. ### 18.1 Core standalone acceptance ```text [ ] install.xml validates for every core plugin. [ ] upgrade.php covers schema evolution for every core plugin. [ ] All foreign-key-like fields are indexed. [ ] All core status fields have documented state machines. [ ] File areas are declared, served, permission-checked, and tested. [ ] Privacy export and deletion/anonymisation are implemented for core tables. [ ] Seed data can be created idempotently without Konnaxion. [ ] Reports can query all required institutional objects without Smart Vote snapshots. [ ] External services have matching classes/external implementations. [ ] Events have matching classes/event implementations. [ ] Scheduled tasks have matching classes/task implementations. [ ] PHPUnit covers repository/service/privacy behavior. [ ] Behat covers major standalone user workflows. [ ] A clean Moodle install can install the package without warnings. [ ] UCKK-Moodle remains functional when Konnaxion bridge and Smart Vote are disabled. ``` ### 18.2 Optional Konnaxion-connected acceptance ```text [ ] Connected-mode tables use canonical names: local_uckk_kx_user_map, local_uckk_kx_object_map, local_uckk_kx_sync_log, uckkassembly_kx_vote_target, uckkassembly_sv_snapshot, uckkassembly_sv_result_audit. [ ] Konnaxion identity/object mappings are privacy-covered and capability-checked. [ ] Konnaxion sync logs redact secrets, avoid raw payload logging by default, and obey retention rules. [ ] Konnaxion timeout, retry, failure, disabled, skipped, and idempotency states are tested. [ ] Smart Vote target mappings require Assembly context and capability checks. [ ] Smart Vote snapshots store reading data separately from final Assembly decisions. [ ] Smart Vote result audit records review, correction, contestation, supersession, and archive linkage. [ ] Smart Vote snapshots and audits can be archived with provenance and contestability. [ ] Reports can show Smart Vote readings only with permission filtering and clear non-authority labels. [ ] Privacy export/delete/redaction covers connected-mode mappings, snapshots, audits, and logs. [ ] Connected-mode absence or outage fails safely and does not fabricate or silently accept Smart Vote results. ``` ## 19. First-pass correction checklist Use this checklist before trying to start Moodle with the generated package: ```text [ ] No PHP controller code exists in amd/src/*.js. [ ] No JavaScript AMD module code exists in *.php page files. [ ] No Markdown fences or prose instructions exist inside PHP source files. [ ] Every version.php component matches its plugin path. [ ] Every declared db/services.php classname exists under classes/external/. [ ] Every db/events.php event class exists under classes/event/. [ ] Every db/tasks.php task class exists under classes/task/. [ ] Every form reference exists under classes/form/ or the correct Moodle form location. [ ] Every privacy string has a matching privacy provider implementation. [ ] php -l passes for all PHP files. [ ] JSON presets validate. [ ] install.xml files validate. [ ] Moodle admin/cli/upgrade.php passes in a disposable development site. [ ] Standalone install passes with Konnaxion bridge disabled. [ ] Connected-mode table names match the canonical names in this document. [ ] No old Konnaxion table names remain: local_uckk_konnaxion_identity_map, local_uckk_konnaxion_object_map, uckkassembly_smartvote_snapshot. [ ] No Smart Vote table or service can overwrite `uckkassembly_decision`. ``` ================================================================================================ FILE: docs/05_roles_permissions_and_security.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: c500955a9ea5f31efd001c304b902ac9cad24c4ba32e38561128d191cf130d8b CONTENT_BYTES: 48509 ================================================================================================ # 05 — Roles, Permissions and Security **Status:** Final access control specification, standalone-first with optional Konnaxion-connected gate **Purpose:** Define Moodle roles, capabilities, contexts, security constraints, optional Konnaxion Smart Vote authority boundaries, and acceptance checks for UCKK-Moodle. This document consumes `docs/11_cross_doc_alignment_registry.md` for shared operating modes, document paths, current code-snapshot capabilities, target connected-mode capabilities, deprecated aliases, and standalone-vs-connected requirements. ## 1. Security principle UCKK symbolic identities must not become uncontrolled Moodle roles. Use Moodle roles only for permission groups. Use badges, profile titles, cohorts, competencies, portfolio titles, archive distinctions, and seeded metadata for symbolic or pedagogical identities. Security decisions must be made by Moodle capabilities checked in the correct Moodle context. No UI label, badge, cohort, symbolic title, preset value, JavaScript state, Konnaxion score, external vote weight, imported result, or request parameter may grant authority by itself. UCKK-Moodle must be secure and usable in standalone mode without Konnaxion. Konnaxion may assist UCKK-Moodle only when Konnaxion-connected mode is enabled. In that mode, Konnaxion may provide Smart Vote readings, EkoH-weighted readings, external analytics, or external identity/object mappings. It must never become the Moodle authority for enrolment, roles, capabilities, grades, badges, competencies, archive validation, integrity decisions, or final Assembly decisions. Canonical Smart Vote authority rule: ```text Konnaxion computes Smart Vote readings. UCKK-Moodle owns Assembly decisions. Archives preserve both, with provenance and contestability. ``` Canonical operating-mode rule: ```text OPERATING_MODE_STANDALONE = standalone_core OPERATING_MODE_KONNAXION_CONNECTED = connected_konnaxion KONNAXION_REQUIRED_FOR_CORE = false SMART_VOTE_REQUIRED_FOR_CORE = false KONNAXION_DEFAULT_STATE = disabled SMART_VOTE_DEFAULT_STATE = disabled unless Konnaxion-connected mode is enabled ``` Standalone mode must support normal UCKK-Moodle operation: courses, roles, challenges, assemblies, archives, integrity review, reporting, privacy, and AI governance. Konnaxion-connected mode adds optional Smart Vote readings and Konnaxion organization signals without replacing Moodle authority. Every privileged operation must answer these questions before implementation is accepted: ```text [ ] Which plugin owns the operation? [ ] Which capability authorizes it? [ ] Which Moodle context is checked? [ ] Which PHP page, external service, CLI command, task, callback, or integration worker performs the check? [ ] Which event is emitted if the operation changes state? [ ] Which PHPUnit or Behat test proves authorized users are allowed? [ ] Which PHPUnit or Behat test proves unauthorized users are denied? [ ] Which privacy provider covers stored personal data? [ ] If Konnaxion is involved, which Moodle record is the source of authority? [ ] If Konnaxion is involved, which imported value is only advisory/read-only? ``` ## 2. Technical roles | Role | Purpose | Implementation rule | |---|---|---| | Administrateur Moodle | Full Moodle administration | Existing Moodle administrator role; not replaced by UCKK. | | Gestionnaire UCKK | Manage UCKK configuration, programs, seed outputs, reports, and approved external integrations | Seeded technical role with explicit UCKK capabilities only. | | Mentor UCKK | Teach, evaluate, guide challenges and assemblies | Course/module-scoped where possible. | | Joueur | Learn, submit proof, join assemblies, complete challenges, cast authorized votes | Learner role; no administrative authority. | | Facilitateur d'Assemblée | Facilitate Assembly workflow where assigned | Module-scoped capability bundle; not a global admin role. | | Archiviste UCKK | Validate, version, and manage archive items | Archive-specific authority; not general content administrator. | | Inquisiteur UCKK | Review integrity cases and issue corrections | Integrity authority with contestability and event logging. | | Observateur | Restricted read-only participant | Read-only role; no restricted integrity access by default. | | Invité public limité | Public-facing read-only access where allowed | Public/guest access only to explicitly public validated material. | | Service d'intégration Konnaxion | Optional connected-mode technical actor for server-to-server exchange | Must not be a human-facing Moodle role; must use restricted service credentials and service-layer capability checks. | The Konnaxion integration service actor exists only when Konnaxion-connected mode is enabled. It must not be enrolled as a normal learner, mentor, manager, Inquisiteur, or administrator. It is a technical integration identity with the minimum service permissions required to exchange mappings and readings. ## 3. Symbolic titles Do not create default Moodle roles for: ```text Bâtisseur Joueur lucide Cartographe de systèmes Architecte du sens Architecte d'opportunités Gardien des systèmes vivants Gardien de la preuve Expert EkoH Voix pondérée Contributeur validé Konnaxion ``` Represent these through: ```text badges profile fields cohorts competency states portfolio titles archive distinctions seeded metadata report labels external mapping metadata ``` Symbolic titles may appear in UI, dashboards, reports, badges, certificates, optional Smart Vote reading panels, and archive records, but they must not bypass `has_capability()`, `require_capability()`, enrolment checks, visibility checks, privacy rules, or Assembly decision rules. ## 4. Capability naming and canonical registry Use Moodle component capability naming: ```text component/capabilityowner:capabilityname ``` Examples: ```text local/uckk:viewcampus mod/uckkchallenge:submitproof mod/uckkassembly:vote mod/uckkassembly:viewsmartvote tool/uckkintegrity:reviewcase report/uckk:viewsmartvotereports ``` Every capability listed as `implemented_now` in this document must exist in the owning plugin's `db/access.php`. Every current `db/access.php` capability must appear in this document or in the plugin-specific implementation specification. Capability names in this section are canonical for the current code snapshot unless explicitly marked as `target_connected_mode`. Other documents must reference this registry instead of redefining conflicting names. Konnaxion-connected capabilities are optional connected-mode capabilities. They must not be required for standalone course, challenge, assembly, archive, integrity, or report workflows. Target connected-mode capabilities must not be treated as implemented until they exist in `db/access.php`, presets, language strings, page/service checks, PHPUnit tests, and Behat visibility tests. ### 4.1 Core UCKK capabilities These capabilities are implemented in the current code snapshot and are required for standalone UCKK-Moodle. ```text local/uckk:viewcampus local/uckk:manageprograms local/uckk:managepathways local/uckk:manageprofiles local/uckk:managecanon local/uckk:viewreports local/uckk:exportdata local/uckk:viewrestricted local/uckk:manageintegrations format/uckk:viewcoursemap format/uckk:viewevidenceindicators format/uckk:viewarchiveindicators format/uckk:viewintegritymarkers format/uckk:configuresections format/uckk:manageblueprint format/uckk:resetsectionnames format/uckk:viewdiagnostics block/uckk_dashboard:addinstance block/uckk_dashboard:myaddinstance block/uckk_dashboard:view block/uckk_dashboard:viewothers block/uckk_dashboard:configure mod/uckkchallenge:addinstance mod/uckkchallenge:view mod/uckkchallenge:createchallenge mod/uckkchallenge:submitproof mod/uckkchallenge:evaluate mod/uckkchallenge:validateintegrity mod/uckkchallenge:archive mod/uckkassembly:addinstance mod/uckkassembly:view mod/uckkassembly:createassembly mod/uckkassembly:proposemotion mod/uckkassembly:amendmotion mod/uckkassembly:vote mod/uckkassembly:publishdecision mod/uckkassembly:contestdecision mod/uckkassembly:archive mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export tool/uckkseed:seed tool/uckkseed:reset tool/uckkseed:validate tool/uckkseed:exportpresets tool/uckkintegrity:view tool/uckkintegrity:opencase tool/uckkintegrity:reviewcase tool/uckkintegrity:assigncase tool/uckkintegrity:issuecorrection tool/uckkintegrity:invalidate tool/uckkintegrity:closecase tool/uckkintegrity:viewrestricted report/uckk:view report/uckk:viewall report/uckk:export aiprovider/uckk:configure aiprovider/uckk:use aiprovider/uckk:viewlogs ``` `local/uckk:manageintegrations` is the implemented integration-administration capability in the current code snapshot. Until narrower Konnaxion capabilities are implemented, Konnaxion bridge configuration, mapping administration, and connected-mode log visibility must be guarded by `local/uckk:manageintegrations` plus service-layer context, privacy, and fail-closed checks. ### 4.2 Optional Konnaxion-connected capability targets These capabilities are target connected-mode capabilities. They are **not implemented in the current code snapshot** unless the capability is explicitly listed in section 4.1. They must not be required for standalone UCKK-Moodle operation. Current implemented Konnaxion/integration administration capability: ```text local/uckk:manageintegrations ``` Target connected-mode capabilities that may be added in a later connected-profile implementation: ```text mod/uckkassembly:requestsmartvote mod/uckkassembly:viewsmartvote mod/uckkassembly:reviewsmartvote mod/uckkassembly:contestsmartvote mod/uckkarchive:archivesmartvote report/uckk:viewsmartvotereports ``` Do not add narrower `local/uckk:*konnaxion*` capabilities unless the migration updates `db/access.php`, presets, language strings, page/service checks, PHPUnit tests, Behat visibility tests, and `DOC_11` together. Capability meanings: | Capability | Meaning | Status | |---|---|---| | `local/uckk:manageintegrations` | Configure and administer optional external integrations, including Konnaxion bridge settings when connected mode is implemented. | implemented now | | `mod/uckkassembly:requestsmartvote` | Request, export, open, refresh, or receive a Smart Vote reading for an Assembly object through the bridge. | target connected-mode | | `mod/uckkassembly:viewsmartvote` | View an authorized Smart Vote reading without private payloads, voter identity, restricted mappings, or secrets. | target connected-mode | | `mod/uckkassembly:reviewsmartvote` | Review, accept as an advisory reading, invalidate, or send to integrity review a Smart Vote result. | target connected-mode | | `mod/uckkassembly:contestsmartvote` | Contest an imported Smart Vote reading or mapping-derived reading. | target connected-mode | | `mod/uckkarchive:archivesmartvote` | Archive a Smart Vote reading/snapshot with provenance and privacy classification. | target connected-mode | | `report/uckk:viewsmartvotereports` | View or export Smart Vote reports and connected-mode audit summaries. | target connected-mode | ### 4.3 Corrected capability spellings The following implemented spelling is canonical for current integration administration: ```text local/uckk:manageintegrations ``` The following spellings are valid target connected-mode spellings if the connected profile is implemented: ```text mod/uckkassembly:requestsmartvote mod/uckkassembly:viewsmartvote mod/uckkassembly:reviewsmartvote mod/uckkassembly:contestsmartvote mod/uckkarchive:archivesmartvote report/uckk:viewsmartvotereports ``` The misspelled or obsolete names below must not be implemented and must not appear in generated code, presets, services, tests, or active UI checks: ```text mod/uckkassembly:viewsmarkvotereading mod/uckkassembly:viewsmartvotereading mod/uckkassembly:exportsmartvotetarget mod/uckkarchive:viewsmartvotesnapshot mod/uckkarchive:archivesmartvotesnapshot ``` ### 4.4 Deprecated capability aliases The following names may appear only in this deprecated-alias section, `DOC_11`, or explicit migration notes. They are deprecated and must not be used in final code, active presets, active services, tests, templates, AMD modules, or runtime checks. | Deprecated or drifting name | Current or target replacement | |---|---| | `local/uckk:managekonnaxion` | `local/uckk:manageintegrations` until a narrower connected-mode migration exists | | `local/uckk:configurekonnaxion` | `local/uckk:manageintegrations` | | `local/uckk:managekonnaxionmappings` | `local/uckk:manageintegrations` until a narrower connected-mode migration exists | | `local/uckk:mapkonnaxionobjects` | `local/uckk:manageintegrations` until a narrower connected-mode migration exists | | `local/uckk:viewkonnaxionstatus` | `local/uckk:manageintegrations` | | `local/uckk:viewkonnaxionlogs` | `local/uckk:manageintegrations` until a narrower connected-mode migration exists | | `local/uckk:syncsmartvote` | restricted service identity plus `local/uckk:manageintegrations` for administration | | `local/uckk:viewsmartvotelogs` | `local/uckk:manageintegrations` | | `mod/uckkassembly:submitmotion` | `mod/uckkassembly:proposemotion` | | `mod/uckkassembly:submitamendment` | `mod/uckkassembly:amendmotion` | | `mod/uckkassembly:submitobjection` | not implemented in current snapshot; use documented objection workflow only after capability migration | | `mod/uckkassembly:managevotes` | not implemented in current snapshot; use service-layer checks around `mod/uckkassembly:vote` until migration | | `mod/uckkassembly:manageminutes` | not implemented in current snapshot; minutes operations require service/page checks until migration | | `mod/uckkassembly:validateintegrity` | not implemented in current snapshot; integrity review belongs to `tool/uckkintegrity:*` capabilities | | `mod/uckkassembly:votesmartvote` | `mod/uckkassembly:requestsmartvote` target for requesting; `mod/uckkassembly:vote` for participant vote | | `mod/uckkassembly:opensmartvote` | `mod/uckkassembly:requestsmartvote` target | | `mod/uckkassembly:exportsmartvotetarget` | `mod/uckkassembly:requestsmartvote` target | | `mod/uckkassembly:importsmartvoteresult` | `mod/uckkassembly:reviewsmartvote` target plus restricted service identity | | `mod/uckkassembly:invalidatesmartvote` | `mod/uckkassembly:reviewsmartvote` target plus integrity-review authority | | `mod/uckkassembly:publishsmartvote` | `mod/uckkassembly:reviewsmartvote` target plus `mod/uckkassembly:publishdecision` | | `mod/uckkassembly:viewsmarkvotereading` | banned typo; no replacement except `mod/uckkassembly:viewsmartvote` target | | `mod/uckkassembly:viewsmartvotereading` | `mod/uckkassembly:viewsmartvote` target | | `mod/uckkarchive:versionitem` | `mod/uckkarchive:reviseitem` | | `mod/uckkarchive:viewsmartvotesnapshot` | `mod/uckkassembly:viewsmartvote` or `report/uckk:viewsmartvotereports`, depending on context, after connected-mode migration | | `mod/uckkarchive:archivesmartvotesnapshot` | `mod/uckkarchive:archivesmartvote` target | | `tool/uckkseed:run` | `tool/uckkseed:seed` | | `tool/uckkseed:dryrun` | `tool/uckkseed:validate` or `tool/uckkseed:seed` depending on mode | | `tool/uckkseed:rollback` | `tool/uckkseed:reset` where reset semantics are explicitly safe | | `tool/uckkintegrity:reviewsmartvote` | `tool/uckkintegrity:reviewcase` plus connected-mode Smart Vote context checks | | `report/uckk:viewsmartvote` | `report/uckk:viewsmartvotereports` target | | `report/uckk:exportsmartvote` | `report/uckk:viewsmartvotereports` target plus export checks | | `report/uckk:viewkonnaxionlogs` | `local/uckk:manageintegrations` until narrower log capability exists | | `mod/uckkchallenge:contest` | not implemented in current snapshot; use documented contest workflow only after capability migration | | `mod/uckkchallenge:viewallsubmissions` | not implemented in current snapshot; use context-aware report/service checks until migration | | `mod/uckkchallenge:manage` | not implemented in current snapshot; use specific implemented capabilities | | `mod/uckkchallenge:publishchallenge` | `mod/uckkchallenge:createchallenge` plus state transition permissions | | `tool/uckkintegrity:invalidatechallenge` | `tool/uckkintegrity:invalidate` plus subject-component check | Final code must fail static review if deprecated names appear in: ```text db/access.php db/services.php classes/external/* classes/event/* classes/local/* classes/service/* templates/* amd/src/* tests/* presets/*.json ``` Deprecated names may appear only in documentation sections explicitly labelled as deprecated aliases or migration notes. ### 4.5 Capability implementation rule For each capability, `db/access.php` must define: ```text captype contextlevel archetypes when appropriate riskbitmask for write, config, XSS, spam, personal-data, or trust-sensitive actions clonepermissionsfrom where a standard Moodle capability is the closest parent ``` A capability is incomplete until at least one test proves: ```text authorized role can perform the action unauthorized role is denied wrong context is denied restricted personal data is not leaked external imported data cannot bypass Moodle authority ``` ## 5. Context levels | Capability family | Default context | Rule | |---|---|---| | Campus viewing | System | May expose public/non-restricted UCKK navigation only. | | Campus configuration | System | Restricted to administrator or Gestionnaire UCKK. | | Program/pathway management | Course category or system | Prefer category context when program belongs to a category; system only for global registries. | | Konnaxion configuration | System | Optional connected-mode only. Endpoint, credentials, global enablement, retention, and fail-closed behavior are system-only and require `local/uckk:manageintegrations` until narrower Konnaxion capabilities are implemented. | | Konnaxion identity mapping | System plus user context | Optional connected-mode only. Mapping writes require `local/uckk:manageintegrations` until narrower mapping capabilities are implemented; reads must respect user privacy and purpose limitation. | | Konnaxion object mapping | Source object context | Optional connected-mode only. Mapping must derive Moodle context from the source Assembly, motion, archive item, report, or profile record. | | Smart Vote reading request | Assembly module context | Optional connected-mode only. Request/export only the minimum target payload needed by Konnaxion; never export hidden evidence unless explicitly permitted. | | Smart Vote result review | Assembly module context | Optional connected-mode only. Imported result is an advisory reading; final decision still requires Assembly decision capability. | | Course format | Course | Must not grant plugin-wide authority. | | Dashboard | Block, user, course, or system | Dashboard is display-only unless a separate owning capability authorizes mutation. | | Challenge activity | Module | Challenge submission, evaluation, validation, contestation, and archive handoff are module-scoped. | | Assembly activity | Module | Motions, votes, Smart Vote readings, decisions, contestation, and archive handoff are module-scoped. | | Archive activity | Module, course, or user | Visibility must be checked per archive item and inherited file visibility. | | Integrity cases | System, course, module, or user | Use the narrowest context matching the subject of the case. | | Reports | Course, category, or system | Course reports must not imply cross-course access. | | AI provider | System plus subject context | Configuration is system-level; use of AI must also check the subject context. | | Seed tool | System | Dry-run, run, rollback, and export are system administrative operations. | When a request includes `courseid`, `cmid`, `userid`, `archiveid`, `caseid`, `programid`, `pathwayid`, `assemblyid`, `motionid`, `konnaxionmappingid`, or `smartvoteresultid`, the implementation must derive the context from the stored record and not trust the request parameter alone. ## 6. Role capability matrix | Capability group | Admin | Gestionnaire | Mentor | Facilitateur | Joueur | Archiviste | Inquisiteur | Observateur | Public limité | Konnaxion service | |---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| | Manage Moodle site | yes | no | no | no | no | no | no | no | no | no | | Manage UCKK programs | yes | yes | no | no | no | no | no | no | no | no | | Configure pathways | yes | yes | no | no | no | no | no | no | no | no | | Configure Konnaxion integration (connected mode) | yes | yes | no | no | no | no | no | no | no | no | | Manage Konnaxion mappings (connected mode) | yes | yes | no | limited | own identity view only | no | audit only | no | no | service-only | | View Konnaxion status/logs (connected mode) | yes | yes | no | limited | no | no | limited | no | no | service-only | | Request/review Smart Vote (connected mode) | yes | yes | no | limited by Assembly | no | no | review only | no | no | service-only | | Teach courses | yes | limited | yes | no | no | no | no | no | no | no | | Submit proof | yes | no | optional | no | yes | no | no | no | no | no | | Evaluate proof | yes | optional | yes | no | no | no | no | no | no | no | | Validate archives | yes | optional | no | no | no | yes | optional | no | no | no | | Open integrity case | yes | yes | yes | yes | yes | yes | yes | no | no | no | | Review integrity case | yes | no | no | no | no | no | yes | no | no | no | | Invalidate challenge | yes | no | no | no | no | no | yes | no | no | no | | Propose Assembly motion | yes | yes | yes | yes | yes when participant | no | no | no | no | no | | Amend Assembly motion | yes | yes | yes | yes | yes when participant | no | no | no | no | no | | Cast Assembly vote | yes | optional | optional | optional | yes when participant | no | no | no | no | no | | Request Smart Vote reading (connected mode) | yes | yes | optional | yes | no | no | review only | no | no | no | | Review imported Smart Vote result (connected mode) | yes | yes | no | yes | no | no | review only | no | no | service-only | | Contest Smart Vote result (connected mode) | yes | yes | yes | yes | yes when affected | yes if archive affected | yes | no | no | no | | Review/invalidate Smart Vote result (connected mode) | yes | no | no | no | no | no | yes | no | no | no | | Publish Assembly decision | yes | yes | yes when facilitator | yes when assigned | no | no | no | no | no | no | | View restricted reports | yes | yes | limited | limited | own only | limited | integrity-related | no | no | no | | View Smart Vote reports (connected mode) | yes | yes | limited | limited | own/public only | archive-related | integrity-related | no | no | no | | Export Smart Vote reports (connected mode) | yes | yes | no | no | no | no | no | no | no | no | | Configure AI provider | yes | no | no | no | no | no | no | no | no | no | | Use governed AI | yes | optional | optional | optional | optional | no | optional | no | no | no | | View AI logs | yes | optional | no | no | no | no | integrity-related | no | no | no | ## 7. Page, service, task, CLI, and integration security gates Every executable entry point must have an explicit security gate. ### 7.1 PHP pages Every user-facing PHP page must: ```text [ ] start with valid PHP only [ ] require config.php through a correct relative path [ ] call require_login() unless intentionally public [ ] resolve the Moodle context from trusted records [ ] call require_capability() for privileged actions [ ] verify sesskey() for state-changing actions [ ] use optional_param()/required_param() with strict PARAM_* types [ ] escape output through Moodle output APIs or templates [ ] avoid authority decisions in JavaScript [ ] avoid trusting external Konnaxion identifiers without local mapping validation ``` ### 7.2 External services and AJAX Every `db/services.php` function must have a matching class under: ```text classes/external/ ``` Each external function must: ```text [ ] validate parameters [ ] derive and validate context [ ] call self::validate_context($context) where appropriate [ ] check capability before reading restricted data or mutating state [ ] return filtered data only [ ] avoid leaking hidden, restricted, or cross-context records [ ] prevent imported Smart Vote readings from changing decisions directly [ ] have PHPUnit tests for allow/deny cases ``` ### 7.3 Scheduled tasks Every `db/tasks.php` class must live under: ```text classes/task/ ``` Scheduled tasks must: ```text [ ] never elevate symbolic roles [ ] never elevate Konnaxion scores into Moodle authority [ ] log privileged state changes [ ] respect component ownership [ ] avoid exposing personal data in logs [ ] be idempotent where possible [ ] fail closed when external integration integrity cannot be verified ``` ### 7.4 CLI scripts Every CLI script must: ```text [ ] be located under cli/ [ ] declare CLI_SCRIPT before requiring config.php [ ] require an administrator or system-level capability when executed through web-equivalent logic [ ] support dry-run for destructive or mass operations [ ] emit auditable output without exposing secrets, tokens, private learner data, private vote payloads, or Konnaxion credentials ``` ### 7.5 Konnaxion integration services Konnaxion integration services are required only in Konnaxion-connected mode. Standalone UCKK-Moodle must install, run, test, and pass security checks with these services disabled or absent from active configuration. All Konnaxion integration code must be service-layer code, not template logic, JavaScript authority, or direct database shortcuts. Required connected-mode security rules: ```text [ ] Konnaxion never writes directly into Moodle source tables. [ ] Moodle never treats Konnaxion `VoteResult` as an Assembly decision. [ ] Moodle stores imported Smart Vote results as versioned snapshots/readings. [ ] Every outbound Smart Vote reading request has a Moodle actor, context, capability, and event. [ ] Every inbound Smart Vote result has a Moodle actor or service identity, context, capability, signature/checksum validation, and event. [ ] Every imported reading can be contested. [ ] Every contested reading can be invalidated by integrity review. [ ] Every final Assembly decision records whether it used, ignored, contradicted, or deferred a Smart Vote reading. [ ] External API credentials use secure Moodle configuration and are never printed in UI, logs, reports, exports, or exceptions. [ ] Network failure, timeout, malformed response, unknown mapping, stale mapping, or failed verification must fail closed. ``` Required connected-mode service classes: ```text local_uckk\service\konnaxion_client local_uckk\service\konnaxion_mapping_service local_uckk\service\konnaxion_sync_service mod_uckkassembly\service\smart_vote_bridge mod_uckkassembly\service\smart_vote_result_validator mod_uckkassembly\service\smart_vote_audit_service ``` ## 8. Inquisiteur constraints The Inquisiteur must be powerful but not arbitrary. Rules: ```text [ ] Inquisiteur can review and pause integrity-sensitive objects. [ ] Inquisiteur can issue corrections. [ ] Inquisiteur can invalidate challenge validation when evidence fails. [ ] Inquisiteur can request archive review. [ ] Inquisiteur can review contested Smart Vote readings. [ ] Inquisiteur can invalidate a Smart Vote snapshot if mapping, source, signature, method, privacy, or procedural integrity fails. [ ] Inquisiteur cannot silently delete evidence. [ ] Inquisiteur cannot erase archive history. [ ] Inquisiteur cannot modify archive history without version record. [ ] Inquisiteur cannot assign themselves unrestricted admin rights. [ ] Inquisiteur cannot close their own contested case without secondary review. [ ] Inquisiteur cannot convert a Smart Vote result into a final Assembly decision. [ ] Inquisiteur decisions are logged and contestable. [ ] Inquisiteur actions generate events. ``` Implementation requirements: ```text tool/uckkintegrity/classes/event/integrity_case_opened.php tool/uckkintegrity/classes/event/integrity_case_reviewed.php tool/uckkintegrity/classes/event/integrity_case_closed.php tool/uckkintegrity/classes/event/integrity_correction_issued.php tool/uckkintegrity/classes/event/challenge_invalidated.php tool/uckkintegrity/classes/event/smart_vote_reviewed.php tool/uckkintegrity/classes/event/smart_vote_invalidated.php tool/uckkintegrity/classes/privacy/provider.php ``` ## 9. Archive security Archive visibility levels: ```text private course cohort program institutional public restricted_integrity restricted_privacy ``` Rules: ```text [ ] Restricted integrity archive items require explicit capability. [ ] Public archive items must be manually validated. [ ] Evidence files inherit archive item visibility unless explicitly restricted further. [ ] Version history must remain available to authorized reviewers. [ ] Version history must not be silently rewritten. [ ] Export requires explicit export capability. [ ] File serving must check item visibility and file ownership context. [ ] Smart Vote snapshots archived from Konnaxion must preserve method, modality, mapping, imported timestamp, importing actor/service, raw-result summary, weighted-result summary, privacy classification, and contestation state. [ ] Smart Vote snapshots must not expose private voter identity, external scores, demographic filters, or EkoH details unless an explicit capability and privacy rule allow it. [ ] Standalone archives may preserve Assembly decisions without any Smart Vote snapshot. [ ] Absence of a Smart Vote reading is valid provenance in standalone mode, not a missing record. ``` Implementation requirements: ```text mod/uckkarchive/db/access.php mod/uckkarchive/classes/event/archive_item_created.php mod/uckkarchive/classes/event/archive_item_validated.php mod/uckkarchive/classes/event/archive_item_versioned.php mod/uckkarchive/classes/event/smart_vote_snapshot_archived.php mod/uckkarchive/classes/privacy/provider.php mod/uckkarchive/tests/* permission checks mod/uckkarchive/tests/behat/* restricted visibility checks ``` ## 10. Konnaxion and Smart Vote security ### 10.1 Integration boundary Konnaxion is an external system. UCKK-Moodle may use it only in Konnaxion-connected mode to compute Smart Vote readings for Assembly motions, decisions, consultations, reports, or other explicitly mapped objects. Konnaxion may provide: ```text external vote target id vote modality raw vote count or raw vote distribution weighted vote reading EkoH-weighted reading metadata result timestamp method/configuration summary result confidence or completeness indicator when available integration mapping reference ``` Konnaxion must not provide or override: ```text Moodle role assignment Moodle capability grants course enrolment challenge validation archive validation integrity closure badge awards competency ratings Assembly final decision Moodle grades privacy deletion authority ``` ### 10.2 Smart Vote states requiring security checks These states exist only in Konnaxion-connected mode. Standalone Assemblies must work without them. The following state transitions are privileged and must be evented: ```text not_mapped → mapped_to_konnaxion mapped_to_konnaxion → target_exported target_exported → smart_vote_open smart_vote_open → smart_vote_closed smart_vote_closed → result_imported result_imported → result_reviewed result_reviewed → result_contested result_reviewed → result_archived result_contested → result_under_integrity_review result_under_integrity_review → result_validated result_under_integrity_review → result_invalidated result_archived → assembly_decision_published ``` Required checks: ```text [ ] Mapping requires `local/uckk:manageintegrations` in the current snapshot, or a later `local/uckk:mapkonnaxionobjects` capability only after the connected-mode capability migration is implemented; source-object capability is still required. [ ] Requesting, exporting, or opening a Smart Vote reading requires `mod/uckkassembly:requestsmartvote`. [ ] Inbound result handling requires `mod/uckkassembly:reviewsmartvote` or restricted service identity. [ ] Result viewing requires `mod/uckkassembly:viewsmartvote` plus visibility rules. [ ] Result contestation requires `mod/uckkassembly:contestsmartvote` or affected-party rights. [ ] Result invalidation requires `mod/uckkassembly:reviewsmartvote` plus integrity-review authority where required. [ ] Archiving requires `mod/uckkarchive:archivesmartvote` and source Assembly authority. [ ] Smart Vote reports require `report/uckk:viewsmartvotereports`. [ ] Final decision publishing requires `mod/uckkassembly:publishdecision` and must not be performed by Konnaxion. ``` ### 10.3 Smart Vote privacy floor The minimum privacy rule is: ```text A normal participant may see the public or participant-visible Smart Vote reading for an Assembly they can access. A normal participant must not automatically see private voter identity, external EkoH weights, demographic filter details, raw exported payloads, hidden mappings, private API errors, or restricted integrity notes. ``` Stored Smart Vote data must be classified as one of: ```text public_reading participant_reading restricted_method_metadata restricted_identity_mapping restricted_vote_payload restricted_integrity_review restricted_privacy_review ``` ### 10.4 Integration identity and credential handling ```text [ ] Konnaxion endpoint URL, API key, client secret, webhook secret, signing key, and token configuration are system-level settings. [ ] Secrets use Moodle secure/password configuration handling. [ ] Secrets must never appear in reports, debug pages, seed logs, exceptions, CLI output, Behat output, PHPUnit failure messages, or downloadable exports. [ ] Webhook or API response verification must validate signature/checksum, target mapping, freshness window, expected modality, expected context, and replay protection. [ ] Failed verification must create an audit event and must not import the result. ``` ### 10.5 Anti-capture rules ```text [ ] Smart Vote cannot make final decisions automatically. [ ] Smart Vote cannot hide minority reports. [ ] Smart Vote cannot suppress contestation. [ ] Smart Vote cannot erase raw Moodle Assembly records. [ ] Smart Vote cannot replace minutes. [ ] Smart Vote cannot bypass Inquisiteur review. [ ] Smart Vote cannot promote external expertise scores into Moodle roles. [ ] Smart Vote cannot award badges or competencies. [ ] Smart Vote cannot publish archives without Archiviste/archive capability. ``` ## 11. AI security AI permissions must be explicit. Rules: ```text [ ] AI cannot run in restricted contexts unless enabled. [ ] AI use must check both aiprovider/uckk:use and the subject-context capability. [ ] AI logs must obey privacy settings. [ ] AI prompts must be redacted according to configuration. [ ] AI output must be visibly labeled non-authoritative. [ ] AI cannot assign grades. [ ] AI cannot close integrity cases. [ ] AI cannot publish assembly decisions. [ ] AI cannot validate archive items. [ ] AI cannot create Moodle roles or assign capabilities. [ ] AI cannot interpret or summarize restricted Smart Vote mappings unless the user has Smart Vote report/log authority. ``` Implementation requirements: ```text ai/provider/uckk/db/access.php ai/provider/uckk/classes/privacy/provider.php ai/provider/uckk/tests/provider_test.php ai/provider/uckk/tests/processor_test.php ``` ## 12. Privacy and personal data Every plugin that stores or exposes user-linked data must implement: ```text classes/privacy/provider.php ``` Required coverage: | Plugin | Privacy coverage required | |---|---| | local_uckk | Profiles, programs, pathways, portfolio/canon relationships, provenance, optional Konnaxion identity mappings, optional Konnaxion object mappings, optional Smart Vote sync logs, imported-reading audit metadata when connected mode is enabled. | | mod_uckkchallenge | Challenge submissions, proof, evaluation, validation, contestation. | | mod_uckkassembly | Motions, votes, objections, amendments, decisions, minutes, optional Smart Vote reading requests, Smart Vote result snapshots, and Smart Vote contestations when connected mode is enabled. | | mod_uckkarchive | Archive items, evidence files, provenance, validation, visibility, optional Smart Vote archived snapshots when connected mode is enabled. | | tool_uckkintegrity | Cases, reviews, corrections, decisions, restricted evidence links, optional Smart Vote integrity review records when connected mode is enabled. | | tool_uckkseed | Seed logs, imported preset metadata, operator actions. | | block_uckk_dashboard | Dashboard preferences or cached user summaries if stored; optional Smart Vote dashboard summaries if cached in connected mode. | | format_uckk | Course-format user preferences or section state if stored. | | report_uckk | Saved filters, exports, report access logs, optional Smart Vote report access logs and Konnaxion log access when connected mode is enabled. | | aiprovider_uckk | Prompt logs, response logs, model/action metadata, redaction state. | Privacy provider tests must prove: ```text [ ] export includes all personal UCKK records for the user [ ] in connected mode, export includes user-linked Konnaxion mappings where Moodle stores them [ ] in connected mode, export includes Moodle-side Smart Vote participation/snapshot records where the user is linked [ ] delete removes or anonymizes user-linked data where Moodle privacy rules require it [ ] in connected mode, Konnaxion identity mappings are deleted, anonymized, or retained according to documented retention rules [ ] restricted integrity records are handled safely [ ] Smart Vote snapshots do not expose unnecessary external weights or private voters [ ] AI logs obey redaction and deletion rules ``` ## 13. Audit logging Every privileged action must create a Moodle event with exact class names. Human-readable audit labels are not enough. ### 13.1 Required audit events Konnaxion and Smart Vote events are required only in Konnaxion-connected mode. ```text local_uckk\event\program_changed local_uckk\event\pathway_assigned local_uckk\event\profile_updated local_uckk\event\konnaxion_identity_mapping_created local_uckk\event\konnaxion_identity_mapping_updated local_uckk\event\konnaxion_identity_mapping_deleted local_uckk\event\konnaxion_object_mapping_created local_uckk\event\konnaxion_object_mapping_updated local_uckk\event\smart_vote_sync_started local_uckk\event\smart_vote_sync_completed local_uckk\event\smart_vote_sync_failed mod_uckkchallenge\event\proof_submitted mod_uckkchallenge\event\proof_evaluated mod_uckkchallenge\event\challenge_validated mod_uckkchallenge\event\challenge_invalidated mod_uckkchallenge\event\challenge_contested mod_uckkassembly\event\assembly_motion_proposed mod_uckkassembly\event\assembly_motion_amended mod_uckkassembly\event\assembly_objection_submitted mod_uckkassembly\event\assembly_vote_cast mod_uckkassembly\event\smart_vote_target_exported mod_uckkassembly\event\smart_vote_opened mod_uckkassembly\event\smart_vote_result_imported mod_uckkassembly\event\smart_vote_result_reviewed mod_uckkassembly\event\smart_vote_result_contested mod_uckkassembly\event\smart_vote_result_invalidated mod_uckkassembly\event\assembly_decision_published mod_uckkassembly\event\assembly_decision_contested mod_uckkassembly\event\assembly_minutes_updated mod_uckkarchive\event\archive_item_created mod_uckkarchive\event\archive_item_validated mod_uckkarchive\event\archive_item_versioned mod_uckkarchive\event\archive_item_exported mod_uckkarchive\event\smart_vote_snapshot_archived tool_uckkintegrity\event\integrity_case_opened tool_uckkintegrity\event\integrity_case_reviewed tool_uckkintegrity\event\integrity_case_closed tool_uckkintegrity\event\integrity_correction_issued tool_uckkintegrity\event\smart_vote_reviewed tool_uckkintegrity\event\smart_vote_invalidated aiprovider_uckk\event\ai_action_requested aiprovider_uckk\event\ai_log_viewed report_uckk\event\report_viewed report_uckk\event\report_exported report_uckk\event\smart_vote_report_viewed report_uckk\event\smart_vote_report_exported tool_uckkseed\event\seed_dry_run_executed tool_uckkseed\event\seed_executed tool_uckkseed\event\seed_rollback_executed ``` Events must include enough object/context information for audit without exposing secrets, private prompt content, private voter identity, external EkoH details, raw private payloads, or unnecessary personal data. ### 13.2 Event naming rule Every event class must use the exact names above unless a later canonical event registry replaces this section. Older human-readable names such as `assembly vote cast` or drifted names such as `vote_submitted` must be mapped to the canonical class name `mod_uckkassembly\event\assembly_vote_cast`. ## 14. Implementation correction gates The next code pass is not accepted until these gates pass. ### 14.1 Filetype correctness ```text [ ] PHP files contain PHP only and start with requires->js_call_amd(...)` reference inside a comment is documentation drift, not executable PHP; it should be cleaned during code polish but must not be classified as the same blocker as PHP controller code inside JavaScript. No JavaScript AMD module may be stored as a .php page. In connected mode, no integrity class may directly write to Konnaxion-owned external systems. No integrity action may bypass Moodle capability checks. ``` ## 3. `mod_uckkarchive` ### 3.1 Archive purpose The archive is the institutional memory of UCKK-Moodle. In standalone mode, it stores: ```text proof decisions minutes challenge results course works portfolio entries Kristals integrity summaries versions public summaries restricted summaries redaction decisions privacy decisions external-source provenance records where applicable ``` When Konnaxion-connected mode is enabled and connected-mode records exist, it may also store: ```text Smart Vote reading snapshots Smart Vote reading methods Smart Vote minority reports Smart Vote contestation summaries Konnaxion mapping provenance packages Konnaxion-derived report snapshots ``` The archive must preserve the distinction between: ```text external raw data computed reading reviewed reading human/institutional decision minority report integrity warning contestation correction supersession ``` ### 3.2 Archive item states ```text draft submitted under_review validated published restricted contested invalidated superseded archived redacted deleted_private ``` When connected-mode records exist, Smart Vote archive items may also use these sub-statuses through metadata or a dedicated field when implemented by the owning plugin: ```text imported accepted_as_reading contested superseded archived invalidated ``` ### 3.3 Archive visibility ```text private course cohort program institutional public restricted_integrity restricted_privacy restricted_smart_vote restricted_konnaxion ``` Visibility must be enforced in: ```text page controllers external service classes renderable/output classes templates file-serving callbacks report queries archive export services Smart Vote report services Konnaxion-derived data views ``` UI hiding is not sufficient. The service layer must enforce visibility before data is returned. ### 3.4 Required implementation files `mod_uckkarchive` must not be considered complete until these files exist and pass tests: ```text mod/uckkarchive/version.php mod/uckkarchive/db/access.php mod/uckkarchive/db/install.xml mod/uckkarchive/db/upgrade.php mod/uckkarchive/db/services.php mod/uckkarchive/lib.php mod/uckkarchive/locallib.php mod/uckkarchive/mod_form.php mod/uckkarchive/classes/form/archive_item_form.php mod/uckkarchive/classes/local/archive_item.php mod/uckkarchive/classes/local/archive_policy.php mod/uckkarchive/classes/local/provenance.php mod/uckkarchive/classes/local/versioning.php mod/uckkarchive/classes/local/smart_vote_archive_policy.php mod/uckkarchive/classes/local/konnaxion_provenance_policy.php mod/uckkarchive/classes/output/archive_view.php mod/uckkarchive/classes/output/archive_item_card.php mod/uckkarchive/classes/external/get_archive.php mod/uckkarchive/classes/external/get_archive_items.php mod/uckkarchive/classes/external/add_item.php mod/uckkarchive/classes/external/validate_item.php mod/uckkarchive/classes/external/export_archive.php mod/uckkarchive/classes/external/archive_smart_vote_snapshot.php mod/uckkarchive/classes/event/archive_item_created.php mod/uckkarchive/classes/event/archive_item_updated.php mod/uckkarchive/classes/event/archive_item_validated.php mod/uckkarchive/classes/event/archive_item_contested.php mod/uckkarchive/classes/event/archive_item_redacted.php mod/uckkarchive/classes/event/smart_vote_snapshot_archived.php mod/uckkarchive/classes/privacy/provider.php mod/uckkarchive/tests/archive_test.php mod/uckkarchive/tests/smart_vote_archive_test.php mod/uckkarchive/tests/konnaxion_provenance_test.php mod/uckkarchive/tests/privacy/provider_test.php mod/uckkarchive/tests/behat/uckkarchive.feature mod/uckkarchive/tests/behat/smart_vote_archive.feature ``` Component rule: ```text mod/uckkarchive/version.php must declare: $plugin->component = 'mod_uckkarchive'; ``` No archive plugin file may declare itself as `mod_uckkassembly`. ## 4. Provenance Every archive item and critical UCKK object must include provenance. Required provenance fields: ```text origin component origin object id author created time source description supporting evidence revision history validation state hash when applicable linked integrity case if applicable privacy classification retention classification visibility state external source family when applicable external system when applicable external object type when applicable external object id when applicable source version when applicable provenance hash when applicable ``` Provenance must be attached to: ```text challenge submissions challenge evaluations assembly motions assembly votes/readings assembly minutes Smart Vote target mappings when connected mode is enabled Smart Vote reading snapshots when connected mode is enabled Smart Vote result audit records when connected mode is enabled Smart Vote minority reports when connected mode is enabled Smart Vote contestations when connected mode is enabled Konnaxion user mappings when connected mode is enabled and retained Konnaxion object mappings when connected mode is enabled Konnaxion sync logs when connected mode is enabled and archived archive items integrity cases AI-generated summaries badges awarded from evidence competency evidence seed-generated institutional objects ``` AI-generated material must record: ```text model/provider when known requesting user request context prompt classification redaction applied human validation state non-authority notice ``` When connected-mode material exists, Konnaxion-derived material must record: ```text external system external object type external object id source version or source timestamp sync status mapping record id reading method raw data reference computed reading reference review state human/institutional decision linkage contestation status archive item id ``` ## 5. Versioning Archive item updates must create version records when: ```text content changes visibility changes validation state changes evidence link changes public summary changes integrity correction is applied privacy redaction is applied retention classification changes AI-generated summary is replaced or validated Smart Vote reading snapshot is accepted as reading Smart Vote reading snapshot is contested Smart Vote reading snapshot is superseded Smart Vote minority report is added or changed Konnaxion mapping provenance changes Konnaxion-derived report snapshot is archived ``` Version records must include: ```text previous state new state changed by change reason timestamp integrity case id if applicable privacy request id if applicable redaction level if applicable hash before when applicable hash after when applicable external source reference when applicable Smart Vote snapshot id when applicable superseded snapshot id when applicable Konnaxion mapping id when applicable ``` Forbidden versioning behavior: ```text overwrite validated public archive item without version remove evidence link without version change visibility without capability check change public summary without audit event delete restricted record without retention decision overwrite Smart Vote snapshot without supersession record remove Konnaxion provenance without audit event change reading method without version change human/institutional decision linkage without Assembly event ``` ## 6. Privacy providers Every plugin storing personal data must implement: ```text classes/privacy/provider.php ``` Plugins that store user data must provide functions to: ```text locate contexts export user data delete data for all users in a context delete data for one user locate users in a context delete data for multiple users when applicable redact restricted integrity data where full export is unsafe preserve legally required institutional records where deletion is not allowed classify Konnaxion-derived identifiers export Smart Vote personal data where permitted anonymize Smart Vote personal data where required retain institutional Smart Vote aggregates where allowed ``` Plugins that do not store personal data must still document that fact through the proper Moodle privacy provider pattern. Privacy providers are required for: ```text local_uckk block_uckk_dashboard mod_uckkchallenge mod_uckkassembly mod_uckkarchive tool_uckkintegrity tool_uckkseed report_uckk aiprovider_uckk format_uckk when preferences or user-specific display state are stored theme_uckk when preferences or user-specific display state are stored ``` When connected-mode records exist, Konnaxion and Smart Vote privacy coverage must be owned as follows: ```text local_uckk covers Konnaxion user mappings, object mappings, sync logs, configuration references, and shared integration records. mod_uckkassembly covers Smart Vote target mappings, reading snapshots, result audit records, contestation links, and decision linkage. mod_uckkarchive covers archived Smart Vote packages, archived provenance, archived minority reports, archived public summaries, redactions, and archive versions. tool_uckkintegrity covers Smart Vote disputes, Konnaxion mapping disputes, restricted case evidence, and review notes. report_uckk covers report caches only if they persist personal or sensitive derived data. ``` ## 7. Personal data map | Plugin | Personal data stored | Privacy provider expectation | | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | `local_uckk` | Player profiles, symbolic roles, pathway assignments, portfolio links; in connected mode, Konnaxion user mappings, Konnaxion object mappings, and Konnaxion sync logs when actor-linked | Full provider | | `block_uckk_dashboard` | Usually none; preferences if stored; connected-mode displayed Smart Vote summaries if cached | Null provider or full provider if preferences/cache exist | | `mod_uckkchallenge` | Submissions, feedback, files, reviews, validation history | Full provider | | `mod_uckkassembly` | Motions, votes/readings, arguments, minutes contributions, contestation records; in connected mode, Smart Vote target mappings, Smart Vote snapshots, and Smart Vote result audit records | Full provider | | `mod_uckkarchive` | Archive items, portfolio items, evidence files, provenance, validation records; in connected mode, archived Smart Vote snapshots, minority reports, and Konnaxion-derived provenance packages | Full provider | | `tool_uckkintegrity` | Case notes, evidence, decisions, parties, restricted records; in connected mode, Smart Vote disputes and Konnaxion mapping disputes | Full provider with redaction rules | | `tool_uckkseed` | Seed logs, import actor, validation results when persisted, preset import errors involving users | Full provider if logs persist; otherwise null provider | | `report_uckk` | No primary data; displays derived data; in connected mode, may cache Smart Vote report rows if explicitly implemented | Null provider or full provider documenting derived/report-only data | | `aiprovider_uckk` | Prompt/response logs if logging enabled, request actor, context | Full provider if logging enabled | | `format_uckk` | Course display state or user preferences if stored | Null provider or full provider if user data exists | | `theme_uckk` | User preferences only if stored | Null provider or full provider if user data exists | ## 8. Privacy export requirements User export must include: ```text profile data pathway assignments challenge submissions challenge feedback assembly contributions assembly participation records where exportable Smart Vote participation records where exportable when connected mode is enabled Smart Vote reading snapshots linked to the user where exportable when connected mode is enabled Smart Vote contestations opened by or about the user when connected mode is enabled Konnaxion user mappings linked to the user when connected mode is enabled Konnaxion sync log entries linked to the user where retained when connected mode is enabled archive items owned by user portfolio items integrity case participation where permitted AI logs related to user where enabled seed/import logs related to user where retained ``` Restricted integrity records may need redaction rules. Export must distinguish: ```text data authored by user data about user data mentioning user data involving multiple parties data imported from Konnaxion when connected mode is enabled computed Smart Vote readings when connected mode is enabled human/institutional Assembly decisions institutional records that cannot be fully removed restricted evidence requiring reviewer-only handling expertise weights requiring restricted handling minority reports requiring deliberative context ``` When Smart Vote export exists, it must never imply that a computed reading is the final Assembly decision unless the Assembly decision record separately says so. ## 9. Deletion and retention Deletion must preserve institutional integrity while respecting privacy requirements. Recommended behavior: ```text User-owned private draft → delete Validated public archive item → anonymize user where required, preserve institutional record when legally allowed Integrity case involving multiple parties → redact according to role and retention policy Assembly vote/readings → preserve aggregate decision, handle personal participation according to policy Smart Vote raw personal participation data → delete, anonymize, or restrict according to policy and source contract Smart Vote computed reading snapshot → preserve institutional snapshot where allowed, redact personal details when required Smart Vote expertise weight linked to user → restrict, anonymize, or delete according to sensitivity and retention policy Konnaxion user mapping → delete or anonymize when no longer needed, unless required for retained audit/provenance Konnaxion object mapping → retain while the mapped institutional object is retained, unless invalidated Konnaxion sync log → retain operationally for bounded period; redact identifiers when no longer needed Challenge submission → delete or anonymize according to validation/publication state AI log → delete, redact, or anonymize according to logging policy and context Seed log → delete or anonymize actor if operational record can be preserved without identity ``` Retention configuration must exist for: ```text integrity cases restricted evidence archive versions Smart Vote reading snapshots Smart Vote result audit records Smart Vote contestations Konnaxion user mappings Konnaxion object mappings Konnaxion sync logs AI logs seed logs privacy request logs audit events ``` Retention configuration must be visible to administrators and covered by tests. When connected-mode records exist, Konnaxion-derived records must not be retained merely because they came from an external system. They must have a Moodle-side retention reason: ```text active mapping active Assembly workflow archived decision provenance open contestation integrity case privacy request required audit period institutional archive policy ``` ## 10. Redaction model Redaction levels: ```text none hide identity remove private notes remove files remove external identifiers remove expertise weights replace with anonymized placeholder restrict to integrity reviewers restrict to privacy reviewers restrict to Smart Vote reviewers delete fully ``` Every redaction action must record: ```text redaction level actor timestamp reason affected component affected object id previous visibility new visibility privacy request id if applicable integrity case id if applicable Smart Vote snapshot id if applicable Konnaxion mapping id if applicable external object id if retained in restricted form ``` Public summaries must never contain: ```text private evidence unredacted sensitive allegations unnecessary personal data AI-generated claims not validated by humans private contact information medical, legal, or protected data unless explicitly lawful and necessary Konnaxion external identifiers unless explicitly approved raw Smart Vote personal data expertise weights linked to identifiable users private minority-report authorship unless explicitly public ``` Redaction must not silently falsify the institutional record. When redaction changes what ordinary viewers can see, the archive must still preserve a restricted provenance trail for authorized reviewers where lawful and policy-permitted. ## 11. Connected-mode Smart Vote contestability model When connected mode is enabled, every Smart Vote reading imported, computed, snapshotted, displayed, reported, or archived in UCKK-Moodle must be contestable. In standalone mode, ordinary Assembly votes/readings, decisions, minutes, and archive records remain contestable without Smart Vote. ### 11.1 Contestable objects ```text Konnaxion user mapping Konnaxion object mapping Konnaxion sync result Smart Vote target mapping Smart Vote raw data reference Smart Vote reading method Smart Vote computed reading Smart Vote expertise weight Smart Vote snapshot Smart Vote report row Smart Vote minority report linkage Smart Vote archive package Assembly decision linkage to Smart Vote ``` ### 11.2 Contestation states ```text none opened under_review waiting_for_response correction_required superseded resolved dismissed archived ``` ### 11.3 Contestation requirements Every contestation must record: ```text contestant context object type object id reason evidence privacy classification retention classification assigned reviewer state decision correction if any superseded object if any archive item id event record ``` ### 11.4 Forbidden contestation behavior ```text hiding a Smart Vote contestation without record publishing contested Smart Vote reading as uncontested using contested Smart Vote reading as final decision authority deleting contested reading before retention decision changing reading method without version changing Konnaxion mapping without audit trail closing contestation without decision note ``` ## 12. Audit reports `report_uckk` must support: ```text archive validation queue contested archive items integrity cases by type integrity cases by state overdue integrity cases challenge invalidations assembly contestations Smart Vote contestations Smart Vote snapshots by state Smart Vote snapshots by reading method Smart Vote supersessions Konnaxion mapping disputes Konnaxion sync failures Konnaxion sync retries AI usage in restricted contexts privacy exports deletion/redaction actions archive version changes capability-sensitive access attempts where logged ``` Reports must enforce: ```text context-aware capabilities restricted record filtering privacy redaction no raw private notes for ordinary users no unrestricted export of integrity data no unrestricted export of Konnaxion identifiers no unrestricted export of raw Smart Vote personal data no presentation of computed Smart Vote reading as final Assembly decision ``` ## 13. Implementation correction gates This document is not complete in code until the implementation passes the core gates. Connected-mode gates are required only when Konnaxion/Smart Vote features are enabled or shipped in the selected release profile. ### 13.1 Filetype gate ```text [ ] Every .php file starts with component. [ ] Every plugin has correct @package values. [ ] Every dependency declaration references an existing plugin. [ ] No plugin file is copied from another plugin without corrected package/component names. [ ] No `mod_uckkarchive` file declares itself as `mod_uckkassembly`. [ ] No Konnaxion/Smart Vote implementation is placed in the wrong owning plugin when connected-mode features are shipped. ``` ### 13.3 Class-layer gate Every referenced namespaced class must exist under the correct plugin `classes/` path. Required class categories: ```text classes/form/* classes/local/* classes/output/* classes/external/* classes/event/* classes/task/* classes/privacy/provider.php ``` No `db/services.php` entry may exist unless the declared external class exists. No `db/tasks.php` entry may exist unless the declared scheduled task class exists. No page controller may import a form, event, policy, output, or local service class that does not exist. Connected-mode Smart Vote and Konnaxion class requirements: ```text [ ] In connected mode, Konnaxion privacy and sync policy classes exist in `local_uckk`. [ ] In connected mode, Smart Vote contestation and snapshot policy classes exist in `mod_uckkassembly`. [ ] In connected mode, Smart Vote archive policy classes exist in `mod_uckkarchive`. [ ] In connected mode, Smart Vote integrity policy classes exist in `tool_uckkintegrity`. [ ] In connected mode, Smart Vote report/export classes exist in `report_uckk`. ``` ### 13.4 Capability gate Every page, external service, file-serving callback, report, and write action must declare and test: ```text context required capability allowed role archetypes forbidden broad role grants risk bitmask where applicable restricted-data behavior ``` In connected mode, Konnaxion and Smart Vote capability checks must include: ```text [ ] `local/uckk:managekonnaxion` [ ] `local/uckk:mapkonnaxionobjects` [ ] `local/uckk:viewkonnaxionlogs` [ ] `mod/uckkassembly:requestsmartvote` [ ] `mod/uckkassembly:viewsmartvote` [ ] `mod/uckkassembly:reviewsmartvote` [ ] `mod/uckkassembly:contestsmartvote` [ ] `mod/uckkarchive:archivesmartvote` [ ] `report/uckk:viewsmartvotereports` ``` These capability checks are not required for standalone records that do not invoke Konnaxion or Smart Vote. ### 13.5 Privacy gate ```text [ ] Every personal data table maps to one privacy provider. [ ] Every privacy provider has PHPUnit coverage. [ ] Export includes all user-owned and user-related UCKK records where permitted. [ ] Delete/anonymize behavior is defined for every table. [ ] Multi-party records have redaction rules. [ ] Restricted integrity data is not exposed in ordinary exports without policy handling. [ ] In connected mode, Konnaxion user mappings are covered by `local_uckk` privacy provider. [ ] In connected mode, Konnaxion sync logs have retention and redaction rules. [ ] In connected mode, Smart Vote snapshots are covered by `mod_uckkassembly` privacy provider. [ ] In connected mode, archived Smart Vote packages are covered by `mod_uckkarchive` privacy provider. [ ] In connected mode, Smart Vote disputes are covered by `tool_uckkintegrity` privacy provider. [ ] In connected mode, Smart Vote reports are privacy-filtered before display and export. ``` ### 13.6 Install and upgrade gate ```text [ ] PHP lint passes. [ ] XMLDB install.xml validates. [ ] upgrade.php is parseable and idempotent. [ ] admin/cli/upgrade.php completes on a clean Moodle target. [ ] admin/cli/purge_caches.php completes after install. [ ] No plugin install warning is accepted as harmless without documentation. [ ] In connected mode, Konnaxion and Smart Vote tables declared in DOC_04 exist in the correct owning plugins. [ ] In connected mode, Konnaxion and Smart Vote privacy metadata is installed with the owning plugins. [ ] No external system direct-write path is required for install or upgrade. ``` ### 13.7 Test gate Required test coverage: ```text PHPUnit: integrity case transitions PHPUnit: archive versioning PHPUnit: archive visibility PHPUnit: privacy export/delete for each data-storing plugin PHPUnit: external service permission checks PHPUnit: AI log redaction when enabled PHPUnit: seed log retention when persisted Connected mode — PHPUnit: Konnaxion user mapping privacy export/delete Connected mode — PHPUnit: Konnaxion object mapping retention Connected mode — PHPUnit: Konnaxion sync log retention and redaction Connected mode — PHPUnit: Smart Vote snapshot export/redaction Connected mode — PHPUnit: Smart Vote contestation workflow Connected mode — PHPUnit: Smart Vote supersession/versioning Connected mode — PHPUnit: Smart Vote report privacy filtering Behat: Inquisiteur opens and closes case Behat: archive item is validated and versioned Behat: contested item produces integrity case Behat: privacy export includes UCKK records Behat: ordinary user cannot see restricted integrity data Behat: AI warning remains non-authoritative Connected mode — Behat: Smart Vote reading can be contested Connected mode — Behat: contested Smart Vote reading is visibly marked Connected mode — Behat: Smart Vote reading does not publish final Assembly decision Connected mode — Behat: Konnaxion sync failure is logged and privacy-filtered ``` ### 13.8 Canonical variable gate ```text [ ] In connected mode, `SOURCE_FAMILY_KONNAXION` is used consistently. [ ] In connected mode, `EXTERNAL_SYSTEM_KONNAXION` is used consistently. [ ] In connected mode, `SMART_VOTE_CANONICAL_RULE` appears in every Smart Vote governance context. [ ] In connected mode, `SMART_VOTE_AUTHORITY` remains `computed_reading_only`. [ ] `ASSEMBLY_AUTHORITY` remains `human_institutional_decision`. [ ] `ARCHIVE_AUTHORITY` remains `provenance_and_contestation_memory`. [ ] `KONNAXION_REQUIRED_FOR_CORE` remains `false`. [ ] `SMART_VOTE_REQUIRED_FOR_CORE` remains `false`. [ ] In connected mode, all `TABLE_KONNAXION_*` and `TABLE_SMART_VOTE_*` names match DOC_00 and DOC_04. [ ] In connected mode, all `SV_*` fields are handled in provenance, privacy, retention, redaction, and archive logic. [ ] In connected mode, all Konnaxion/Smart Vote capabilities match DOC_05. [ ] No alternate table, service, event, or capability names are introduced locally in DOC_08. ``` ## 14. Definition of done ### 14.1 Core standalone definition of done ```text [ ] Integrity cases work end-to-end without Konnaxion enabled. [ ] Archive items are versioned. [ ] Archive items enforce visibility in service layer and UI. [ ] Integrity actions generate events. [ ] Privacy providers export and delete personal data for core UCKK-Moodle records. [ ] Public archive items cannot be silently modified. [ ] Restricted integrity information is not exposed to ordinary users. [ ] Reports support governance review without requiring Smart Vote records. [ ] Every required core class referenced by pages/services/tasks exists. [ ] Every core db/services.php declaration has a matching external class. [ ] Every core db/tasks.php declaration has a matching task class. [ ] PHP/JS filetype gates pass. [ ] Moodle install and upgrade pass on a clean target with Konnaxion disabled. [ ] PHPUnit and Behat coverage exists for standalone integrity, archive, and privacy workflows. [ ] Standalone archives may preserve Assembly decisions without any Smart Vote snapshot. [ ] Absence of a Smart Vote reading is valid provenance, not a missing record. [ ] `KONNAXION_REQUIRED_FOR_CORE` remains `false`. [ ] `SMART_VOTE_REQUIRED_FOR_CORE` remains `false`. ``` ### 14.2 Optional Konnaxion-connected definition of done ```text [ ] Konnaxion-derived records have privacy, retention, redaction, and provenance rules. [ ] Smart Vote readings are archived as readings, not final decisions. [ ] Smart Vote snapshots preserve raw data reference, reading method, computed reading, contestation status, and provenance. [ ] Smart Vote contestations open integrity-review paths. [ ] Smart Vote supersessions create version records. [ ] Konnaxion mappings can be reviewed and contested. [ ] Konnaxion sync logs are privacy-filtered and retention-bound. [ ] Reports never expose raw Smart Vote or Konnaxion data beyond capability and privacy rules. [ ] Archives preserve both Konnaxion-derived readings and UCKK-Moodle Assembly decisions with provenance and contestability when Smart Vote readings exist. [ ] Connected-mode tests prove that disabling Konnaxion hides or disables Smart Vote-specific actions without breaking core archive and integrity workflows. ``` --- ## Update note — 2026-05-13 filetype-gate clarification This revision keeps the real blocker intact: executable PHP or Moodle page-controller code must not appear in AMD JavaScript files, and AMD JavaScript modules must not be stored as `.php` pages. It also prevents false classification of documentation examples or comment-only `$PAGE->requires->js_call_amd(...)` references as equivalent to executable PHP-in-JS blockers. ================================================================================================ FILE: docs/09_integrations_reporting_delivery.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 9aab3e9a2bc609b99221559af7e1721294da6f716c2fca599710e51b74d96b8a CONTENT_BYTES: 67672 ================================================================================================ # 09 — Integrations, Reporting and Delivery **Status:** Final delivery specification with standalone/connected-mode alignment **Purpose:** Define UCKK-Moodle standalone delivery, optional Konnaxion Smart Vote connected-mode integration, AI integration, reporting, seed execution, testing, release, implementation-readiness gates, canonical variable resolution, and acceptance. ## 0. Canonical variables consumed by this document This document consumes the canonical variables defined by `00_master_execution_doctrine.md` and `11_cross_doc_alignment_registry.md`. It may add delivery detail, but it must not rename, invert, or silently redefine the root variables. Shared document paths, operating modes, capability aliases, table names, service names, deprecated names, and standalone-vs-connected requirements are resolved by `DOC_11`. This document must not override `DOC_11`. ### 0.1 Document variables | Variable | Canonical value | Use in this document | |---|---|---| | `DOC_00` | `00_master_execution_doctrine.md` | Root doctrine and correction authority. | | `DOC_04` | `04_data_model_and_storage.md` | Canonical table, enum, state-machine, and storage definitions. | | `DOC_05` | `05_roles_permissions_and_security.md` | Canonical capability registry. | | `DOC_07` | `07_challenges_and_assemblies.md` | Canonical Assembly, Smart Vote, decision, and contestation workflows. | | `DOC_08` | `08_integrity_archives_and_privacy.md` | Canonical archive, privacy, retention, redaction, and integrity rules. | | `DOC_09` | `09_integrations_reporting_delivery.md` | This integration, reporting, delivery, testing, and acceptance document. | | `DOC_10` | `10_konnaxion_smart_vote_integration_contract.md` | Optional Konnaxion Smart Vote connected-mode integration contract. | | `DOC_11` | `11_cross_doc_alignment_registry.md` | Cross-document variable, alias, implementation-status, and drift registry. | | `LEGACY_DOC_10` | `10_implementation_correction_plan.md` | Deprecated. Must not be used as the active product-tree target. | ### 0.2 Source-family variables | Variable | Canonical value | Rule | |---|---|---| | `SOURCE_FAMILY_UCKK_CANON` | `UCKK canon` | Governs UCKK meaning, pedagogy, governance, and symbolic boundaries. | | `SOURCE_FAMILY_KONNAXION` | `Konnaxion external source family` | External source of truth for Konnaxion-side Smart Vote objects and semantics. | | `SOURCE_FAMILY_MOODLE_DOCS` | `Moodle developer documentation` | Governs Moodle implementation mechanics. | | `EXTERNAL_SYSTEM_KONNAXION` | `Konnaxion` | External system integrated only through Moodle services. | | `EXTERNAL_SIGNAL_EKOH` | `EkoH` | External ecosystem context or signal source only where explicitly mapped. | ### 0.3 Boundary variables | Variable | Canonical value | |---|---| | `PRODUCT_SCOPE` | `UCKK-Moodle is the Moodle campus implementation of UCKK.` | | `SMART_VOTE_CANONICAL_RULE` | `Konnaxion computes Smart Vote readings. UCKK-Moodle owns Assembly decisions. Archives preserve both, with provenance and contestability.` | | `SMART_VOTE_AUTHORITY` | `computed_reading_only` | | `ASSEMBLY_AUTHORITY` | `human_institutional_decision` | | `ARCHIVE_AUTHORITY` | `provenance_and_contestation_memory` | | `DIRECT_WRITE_RULE` | `external_systems_never_write_moodle_source_tables` | | `PERMISSION_RULE` | `moodle_capabilities_remain_authoritative` | | `OPERATING_MODE_STANDALONE` | `standalone_core` | | `OPERATING_MODE_KONNAXION_CONNECTED` | `connected_konnaxion` | | `KONNAXION_REQUIRED_FOR_CORE` | `false` | | `SMART_VOTE_REQUIRED_FOR_CORE` | `false` | | `KONNAXION_DEFAULT_STATE` | `disabled` | | `SMART_VOTE_DEFAULT_STATE` | `disabled unless Konnaxion bridge is enabled` | ### 0.4 Plugin ownership variables | Variable | Canonical owner | Responsibilities | |---|---|---| | `KONNAXION_BRIDGE_OWNER` | `local_uckk` | Configuration, authentication settings, endpoint client, object mapping, sync logs, shared integration services. | | `SMART_VOTE_WORKFLOW_OWNER` | `mod_uckkassembly` | Smart Vote reading requests, vote-target mapping, snapshots, review, contestation, and Assembly linkage. | | `ASSEMBLY_DECISION_OWNER` | `mod_uckkassembly` | Motions, deliberation, decision publication, minority report, and decision contestability. | | `SMART_VOTE_ARCHIVE_OWNER` | `mod_uckkarchive` | Archive records and file areas for Smart Vote snapshots, decisions, minutes, and provenance packages. | | `SMART_VOTE_REPORT_OWNER` | `report_uckk` | Smart Vote reports, institutional exports, filters, and privacy-aware visibility. | | `SMART_VOTE_INTEGRITY_OWNER` | `tool_uckkintegrity` | Integrity warnings, contested readings, correction cases, and restricted review workflows. | | `SMART_VOTE_SEED_OWNER` | `tool_uckkseed` | Idempotent presets for capabilities, mappings, report definitions, and integration defaults. | | `SMART_VOTE_PRIVACY_OWNER` | every storing plugin | Each plugin that stores personal data owns its privacy provider, export, delete, anonymisation, and retention tests. | ### 0.5 Konnaxion object variables | Variable | Canonical value | Moodle-side use | |---|---|---| | `KONNAXION_OBJECT_VOTE` | `Vote` | External vote object mapped to a Moodle-side vote target or reading source. | | `KONNAXION_OBJECT_VOTE_MODALITY` | `VoteModality` | External voting modality/method mapped to a Moodle-side reading method. | | `KONNAXION_OBJECT_VOTE_RESULT` | `VoteResult` | External result mapped into a Moodle-side Smart Vote reading snapshot. | | `KONNAXION_OBJECT_INTEGRATION_MAPPING` | `IntegrationMapping` | External mapping object mirrored by Moodle-side mapping tables. | | `KONNAXION_EXTERNAL_ID_FIELD` | `externalid` | Stores the Konnaxion identifier; never stores secrets. | | `KONNAXION_EXTERNAL_TYPE_FIELD` | `externaltype` | Stores the Konnaxion object type. | | `KONNAXION_SOURCE_VERSION_FIELD` | `sourceversion` | Stores the external source version, revision, or timestamp where available. | | `KONNAXION_SYNC_STATUS_FIELD` | `syncstatus` | Stores Moodle-side sync state using the canonical sync enum. | | `KONNAXION_PROVENANCE_HASH_FIELD` | `provenancehash` | Stores integrity hash for imported snapshots or mapped records where needed. | Additional Konnaxion objects such as `UserExpertiseScore`, `UserEthicsScore`, `ConfidentialitySetting`, and `ScoreHistory` may be consumed only as mapped metadata. They do not become Moodle authority and must not be stored without explicit privacy, retention, visibility, and contestation rules. ### 0.6 Moodle-side Konnaxion table variables | Variable | Canonical table | Owner | Purpose | |---|---|---|---| | `TABLE_KONNAXION_USER_MAP` | `local_uckk_kx_user_map` | `local_uckk` | Maps Moodle users to Konnaxion identities without exposing unnecessary external personal data. | | `TABLE_KONNAXION_OBJECT_MAP` | `local_uckk_kx_object_map` | `local_uckk` | Maps Moodle objects to Konnaxion objects. | | `TABLE_KONNAXION_SYNC_LOG` | `local_uckk_kx_sync_log` | `local_uckk` | Logs sync attempts, failures, retries, endpoint responses, and idempotency keys. | | `TABLE_SMART_VOTE_TARGET_MAP` | `uckkassembly_kx_vote_target` | `mod_uckkassembly` | Maps Assembly motions, decisions, or deliberation objects to Konnaxion vote targets. | | `TABLE_SMART_VOTE_SNAPSHOT` | `uckkassembly_sv_snapshot` | `mod_uckkassembly` | Stores Moodle-side immutable Smart Vote reading snapshots. | | `TABLE_SMART_VOTE_RESULT_AUDIT` | `uckkassembly_sv_result_audit` | `mod_uckkassembly` | Stores review, correction, contestation, and supersession trail for Smart Vote results. | The abbreviation `kx` is allowed only in table and internal variable names. User-facing documentation and UI must use `Konnaxion`. ### 0.7 Smart Vote reading variables | Variable | Canonical field/key | Rule | |---|---|---| | `SV_RAW_DATA` | `raw_data` | Imported or referenced source facts before interpretation. | | `SV_READING_METHOD` | `reading_method` | The declared method, modality, weighting, or algorithmic reading rule. | | `SV_COMPUTED_READING` | `computed_reading` | The non-sovereign Smart Vote output. | | `SV_EXPERTISE_WEIGHT` | `expertise_weight` | Any weighted-reading factor; personal or sensitive where linkable to a user. | | `SV_HUMAN_DECISION` | `human_institutional_decision` | Moodle-side Assembly decision; must not be overwritten by Smart Vote. | | `SV_MINORITY_REPORT` | `minority_report` | Documented minority position or dissenting signal. | | `SV_INTEGRITY_WARNING` | `integrity_warning` | Warning or flag that may open integrity review but is not itself a sanction. | | `SV_CONTESTATION_STATUS` | `contestation_status` | Contestation state for the snapshot or decision linkage. | | `SV_ARCHIVE_ITEM_ID` | `archiveitemid` | Link to preserved archive item when archived. | ### 0.8 Status and state variables | Variable | Allowed values | Owner | |---|---|---| | `KONNAXION_SYNC_STATUS_ENUM` | `queued`, `running`, `succeeded`, `failed`, `retry_waiting`, `skipped`, `disabled` | `local_uckk` | | `KONNAXION_MAPPING_STATUS_ENUM` | `draft`, `active`, `suspended`, `superseded`, `archived`, `invalidated` | `local_uckk` | | `SMART_VOTE_TARGET_STATUS_ENUM` | `draft`, `mapped`, `active`, `closed`, `archived`, `contested` | `mod_uckkassembly` | | `SMART_VOTE_SNAPSHOT_STATUS_ENUM` | `imported`, `under_review`, `accepted_as_reading`, `contested`, `superseded`, `archived`, `invalidated` | `mod_uckkassembly` | | `SMART_VOTE_AUDIT_STATUS_ENUM` | `recorded`, `reviewed`, `corrected`, `contested`, `resolved` | `mod_uckkassembly` | ### 0.9 Capability variables | Variable | Canonical capability | Owner | |---|---|---| | `CAP_MANAGE_KONNAXION` | `local/uckk:manageintegrations` | `local_uckk` | | `CAP_MAP_KONNAXION_OBJECTS` | `local/uckk:manageintegrations` | `local_uckk` | | `CAP_VIEW_KONNAXION_LOGS` | `local/uckk:manageintegrations` | `local_uckk` | | `CAP_REQUEST_SMART_VOTE` | `mod/uckkassembly:requestsmartvote` | `mod_uckkassembly` | | `CAP_VIEW_SMART_VOTE` | `mod/uckkassembly:viewsmartvote` | `mod_uckkassembly` | | `CAP_REVIEW_SMART_VOTE` | `mod/uckkassembly:reviewsmartvote` | `mod_uckkassembly` | | `CAP_CONTEST_SMART_VOTE` | `mod/uckkassembly:contestsmartvote` | `mod_uckkassembly` | | `CAP_ARCHIVE_SMART_VOTE` | `mod/uckkarchive:archivesmartvote` | `mod_uckkarchive` | | `CAP_VIEW_SMART_VOTE_REPORTS` | `report/uckk:viewsmartvotereports` | `report_uckk` | The first three Konnaxion capability variables intentionally map to the current implemented generic integration capability, `local/uckk:manageintegrations`, until narrower Konnaxion-specific capabilities are added to code and presets. Narrower aliases such as `local/uckk:managekonnaxion`, `local/uckk:mapkonnaxionobjects`, and `local/uckk:viewkonnaxionlogs` must not be treated as implemented capabilities unless `DOC_11`, `DOC_05`, `db/access.php`, presets, language strings, PHPUnit access tests, and Behat visibility tests are updated together. Additional split capabilities may be added only if they are added to `DOC_05`, `DOC_11`, `presets/capabilities.json`, language strings, PHPUnit access tests, and Behat visibility tests. They must not replace the canonical capabilities above without a documented doctrine update. ### 0.10 Service and event variables | Variable | Canonical name | Owner | |---|---|---| | `SERVICE_CREATE_KONNAXION_MAPPING` | `local_uckk_create_konnaxion_mapping` | `local_uckk` | | `SERVICE_GET_KONNAXION_MAPPING` | `local_uckk_get_konnaxion_mapping` | `local_uckk` | | `SERVICE_SYNC_KONNAXION` | `local_uckk_sync_konnaxion` | `local_uckk` | | `SERVICE_REQUEST_SMART_VOTE_READING` | `mod_uckkassembly_request_smart_vote_reading` | `mod_uckkassembly` | | `SERVICE_IMPORT_SMART_VOTE_SNAPSHOT` | `mod_uckkassembly_import_smart_vote_snapshot` | `mod_uckkassembly` | | `SERVICE_CONTEST_SMART_VOTE_SNAPSHOT` | `mod_uckkassembly_contest_smart_vote_snapshot` | `mod_uckkassembly` | | `SERVICE_GET_SMART_VOTE_REPORT` | `report_uckk_get_smart_vote_report` | `report_uckk` | | `EVENT_KONNAXION_MAPPING_CREATED` | `local_uckk\event\konnaxion_mapping_created` | `local_uckk` | | `EVENT_KONNAXION_SYNC_COMPLETED` | `local_uckk\event\konnaxion_sync_completed` | `local_uckk` | | `EVENT_SMART_VOTE_READING_REQUESTED` | `mod_uckkassembly\event\smart_vote_reading_requested` | `mod_uckkassembly` | | `EVENT_SMART_VOTE_SNAPSHOT_IMPORTED` | `mod_uckkassembly\event\smart_vote_snapshot_imported` | `mod_uckkassembly` | | `EVENT_SMART_VOTE_SNAPSHOT_CONTESTED` | `mod_uckkassembly\event\smart_vote_snapshot_contested` | `mod_uckkassembly` | | `EVENT_SMART_VOTE_SNAPSHOT_ARCHIVED` | `mod_uckkassembly\event\smart_vote_snapshot_archived` | `mod_uckkassembly` | ### 0.11 Preset registry variables | Variable | Canonical preset | Required by | |---|---|---| | `PRESET_CAPABILITIES` | `presets/capabilities.json` | Roles, capabilities, tests, seed tool. | | `PRESET_STATE_MACHINES` | `presets/state_machines.json` | Workflow statuses and transitions. | | `PRESET_EVENTS` | `presets/events.json` | Event-class registry and tests. | | `PRESET_KONNAXION_MAPPINGS` | `presets/konnaxion_mappings.json` | Connected-mode Konnaxion object map defaults and validation fixtures only. | | `PRESET_PRIVACY_RETENTION` | `presets/privacy_retention.json` | Privacy, export, deletion, anonymisation, redaction, and retention tests. | | `PRESET_EXPORTS` | `presets/exports.json` | Report/export definitions and acceptance evidence. | ## 1. Integration principle UCKK-Moodle may connect to external systems, but Moodle remains the campus authority for learning records, capabilities, workflows, evidence, archives, reports, privacy behavior, and institutional decisions. External systems may assist. They must not silently replace Moodle records. No external integration may bypass: ```text Moodle capabilities Moodle contexts UCKK provenance rules archive rules integrity review privacy export/delete behavior Moodle event logging Assembly decision workflow contestation workflow retention policy ``` Canonical external-authority rule: ```text Konnaxion computes Smart Vote readings. UCKK-Moodle owns Assembly decisions. Archives preserve both, with provenance and contestability. ``` This document uses `EXTERNAL_SYSTEM_KONNAXION` as an external source, not as a Moodle authority. UCKK-Moodle has two delivery profiles: ```text standalone_core connected_konnaxion ``` `standalone_core` is the mandatory product baseline. It must install, seed, teach, deliberate, archive, report, enforce privacy, and pass tests without Konnaxion. `connected_konnaxion` is an optional integration profile. It adds Konnaxion Smart Vote readings, EkoH/advisory signals where explicitly mapped, Konnaxion sync/mapping services, and connected-mode reports. It must not be required for core installation or ordinary UCKK-Moodle operation. ## 2. Optional Konnaxion Smart Vote connected-mode integration All requirements in this section apply to `connected_konnaxion`. They are not release blockers for `standalone_core` unless the connected profile is enabled, packaged, or claimed as supported. In `standalone_core`, Konnaxion and Smart Vote UI actions must be hidden or disabled, Konnaxion sync must not run, and missing Konnaxion configuration must not block Moodle installation, seed execution, Assembly decisions, Archive preservation, Integrity review, reporting, privacy export/delete, or tests. ### 2.1 Component ownership When `connected_konnaxion` is enabled, the Konnaxion bridge is owned by: ```text KONNAXION_BRIDGE_OWNER = local_uckk ``` In `connected_konnaxion`, the bridge is consumed by: ```text SMART_VOTE_WORKFLOW_OWNER = mod_uckkassembly SMART_VOTE_ARCHIVE_OWNER = mod_uckkarchive SMART_VOTE_INTEGRITY_OWNER = tool_uckkintegrity SMART_VOTE_REPORT_OWNER = report_uckk SMART_VOTE_SEED_OWNER = tool_uckkseed ``` Do not create a separate plugin for the first integration pass unless the Konnaxion bridge becomes independently distributable. Until then, `local_uckk` owns: ```text Konnaxion configuration API access identity mapping object mapping sync log endpoint client shared service contracts authentication settings timeout and failure behavior retry and idempotency policy ``` `mod_uckkassembly` owns: ```text Smart Vote reading request vote-target mapping snapshot import reading review reading contestation Assembly linkage decision separation ``` `mod_uckkarchive` owns: ```text Smart Vote archive package snapshot archive item decision archive item minutes archive item provenance package visibility and retention enforcement ``` `tool_uckkintegrity` owns: ```text integrity warnings anomaly review restricted correction workflow invalidated reading trail privacy/integrity escalation ``` `report_uckk` owns: ```text Smart Vote institutional reports Smart Vote export views privacy-aware report filters delivery evidence exports ``` ### 2.2 Integration boundary Konnaxion is an external collective-intelligence and Smart Vote system. UCKK-Moodle may use Konnaxion for: ```text vote modalities vote collection or vote import raw vote counts weighted vote readings EkoH-derived weight metadata where authorized Smart Vote result snapshots integration mapping identifiers anomaly metadata external result provenance ``` Konnaxion must not become Moodle authority. Konnaxion must not directly perform these UCKK-Moodle actions: ```text publish Assembly decisions award Moodle badges certify competencies close integrity cases modify archive records modify challenge status modify course completion change Moodle roles or capabilities silently create Moodle records silently delete Moodle records silently rewrite Moodle records bypass Moodle privacy export/delete behavior bypass Moodle event logging write directly into Moodle source tables ``` The canonical direct-write rule is: ```text DIRECT_WRITE_RULE = external_systems_never_write_moodle_source_tables ``` The canonical permission rule is: ```text PERMISSION_RULE = moodle_capabilities_remain_authoritative ``` ### 2.3 Konnaxion objects recognized by UCKK-Moodle UCKK-Moodle must recognize the following Konnaxion-side objects through a stable API, approved SDK, or dedicated adapter: ```text KONNAXION_OBJECT_VOTE = Vote KONNAXION_OBJECT_VOTE_MODALITY = VoteModality KONNAXION_OBJECT_VOTE_RESULT = VoteResult KONNAXION_OBJECT_INTEGRATION_MAPPING = IntegrationMapping ``` Additional Konnaxion-side metadata objects may be consumed only when authorized and explicitly mapped: ```text UserExpertiseScore UserEthicsScore ConfidentialitySetting ScoreHistory ``` These additional objects are metadata sources only. They must not become Moodle authority and must not be stored unless the storing plugin implements: ```text privacy metadata declaration privacy export deletion or anonymisation behavior retention expiry visibility restriction audit event coverage contestation or correction path ``` UCKK-Moodle must not query or mutate Konnaxion database tables directly. Table names from Konnaxion documentation are semantic references only. The Moodle bridge must use: ```text Konnaxion API endpoints approved Konnaxion SDK dedicated adapter class documented mock adapter for tests ``` ### 2.4 Smart Vote authority rule Smart Vote is a reading method inside an Assembly workflow. It is not an automatic decision publisher. Every Smart Vote use must preserve this separation: | Layer | Variable | Owner | Meaning | |---|---|---|---| | Raw votes | `SV_RAW_DATA` | Konnaxion or Moodle proxy service | Individual or aggregated participation input. | | Reading method | `SV_READING_METHOD` | Konnaxion and `mod_uckkassembly` | Declared modality, weighting, or reading method. | | Computed reading | `SV_COMPUTED_READING` | Konnaxion | Non-sovereign Smart Vote output. | | Assembly interpretation | `SV_HUMAN_DECISION` preparation layer | `mod_uckkassembly` | Human/institutional interpretation of the result. | | Final decision | `ASSEMBLY_AUTHORITY` | `mod_uckkassembly` | UCKK decision after required capability and state checks. | | Minority report | `SV_MINORITY_REPORT` | `mod_uckkassembly` and `mod_uckkarchive` | Documented dissenting or alternative interpretation. | | Memory | `ARCHIVE_AUTHORITY` | `mod_uckkarchive` | Archived result, decision, provenance, minority report, and contestation path. | | Integrity review | `SV_INTEGRITY_WARNING` | `tool_uckkintegrity` | Dispute, anomaly, correction, invalidation, or privacy review. | Smart Vote may inform a decision. Smart Vote must not: ```text publish the final decision award recognition validate evidence close contestation override capability checks replace Assembly reasoning erase minority reports hide integrity warnings ``` ### 2.5 Connected-mode admin settings `local_uckk` must define these settings when connected-mode support is included: ```text enable_konnaxion_bridge konnaxion_base_url konnaxion_api_client_id konnaxion_api_secret konnaxion_api_timeout_seconds konnaxion_verify_tls konnaxion_fail_closed konnaxion_log_metadata konnaxion_log_payloads konnaxion_retention_days konnaxion_pseudonymize_user_ids smartvote_enabled smartvote_default_modality smartvote_allowed_assembly_types smartvote_require_archive_snapshot smartvote_require_integrity_review_on_anomaly smartvote_allow_proxy_vote_from_moodle smartvote_allow_external_vote_portal smartvote_import_requires_review smartvote_archive_on_decision_publish smartvote_max_result_age_seconds ``` Secrets must use Moodle secure/password configuration handling. Secrets must not appear in: ```text reports debug output seed logs archive exports privacy exports except where legally required exception pages AI prompts AI responses Moodle event descriptions Behat output PHPUnit failure dumps scheduled task output visible to non-admins ``` Payload logging must be disabled by default. If payload logging is enabled, the privacy provider must cover: ```text metadata declaration export deletion or anonymisation retention expiry restricted visibility administrator warning test coverage ``` ### 2.6 Connected-mode capabilities The canonical minimum Konnaxion and Smart Vote capabilities for `connected_konnaxion` are: ```text CAP_MANAGE_KONNAXION = local/uckk:manageintegrations CAP_MAP_KONNAXION_OBJECTS = local/uckk:manageintegrations CAP_VIEW_KONNAXION_LOGS = local/uckk:manageintegrations CAP_REQUEST_SMART_VOTE = mod/uckkassembly:requestsmartvote CAP_VIEW_SMART_VOTE = mod/uckkassembly:viewsmartvote CAP_REVIEW_SMART_VOTE = mod/uckkassembly:reviewsmartvote CAP_CONTEST_SMART_VOTE = mod/uckkassembly:contestsmartvote CAP_ARCHIVE_SMART_VOTE = mod/uckkarchive:archivesmartvote CAP_VIEW_SMART_VOTE_REPORTS = report/uckk:viewsmartvotereports ``` `tool_uckkintegrity` must add or map explicit integrity capabilities for: ```text tool/uckkintegrity:reviewsmartvoteanomaly tool/uckkintegrity:pausesmartvotereading tool/uckkintegrity:invalidatesmartvotereading ``` If the implementation needs split capabilities for import, export, status viewing, or identity-map management, they must be added to the canonical capability registry and must not replace the canonical minimum capabilities. Every capability must be: ```text declared in the owning plugin's db/access.php represented in DOC_05 represented in presets/capabilities.json covered by language strings covered by denied-path PHPUnit tests covered by allowed-path PHPUnit tests covered by Behat visibility tests checked in every related page and service ``` ### 2.7 Connected-mode Moodle-side mapping contract In `connected_konnaxion`, UCKK-Moodle must maintain Moodle-side mappings for Konnaxion identities, objects, vote targets, snapshots, and sync logs. The canonical storage definitions belong in `DOC_04`. This document defines delivery behavior. Canonical Moodle-side tables are: ```text TABLE_KONNAXION_USER_MAP = local_uckk_kx_user_map TABLE_KONNAXION_OBJECT_MAP = local_uckk_kx_object_map TABLE_KONNAXION_SYNC_LOG = local_uckk_kx_sync_log TABLE_SMART_VOTE_TARGET_MAP = uckkassembly_kx_vote_target TABLE_SMART_VOTE_SNAPSHOT = uckkassembly_sv_snapshot TABLE_SMART_VOTE_RESULT_AUDIT = uckkassembly_sv_result_audit ``` Identity mapping must support: ```text Moodle userid Konnaxion externalid or stable pseudonymous id externaltype sourceversion verification status verification actor verification timestamp revocation status conflict status syncstatus provenancehash privacy export behavior privacy deletion or anonymisation behavior ``` Object mapping must support: ```text Moodle component object type object id context id Konnaxion target type Konnaxion target id Konnaxion module/context mapping details mapping status created by timecreated timemodified sourceversion syncstatus provenancehash ``` Target identifiers must be stable and reproducible. Motion-level readings use: ```text konnaxiontargettype = uckk_assembly_motion konnaxiontargetid = moodle:{siteid}:mod_uckkassembly:{cmid}:motion:{motionid} ``` Assembly-level readings use: ```text konnaxiontargettype = uckk_assembly konnaxiontargetid = moodle:{siteid}:mod_uckkassembly:{cmid}:assembly:{assemblyid} ``` The mapping payload sent to Konnaxion must include enough metadata to verify: ```text Moodle site component context activity module Assembly motion callback policy visibility policy privacy notice state ``` The mapping payload must not expose unnecessary personal data. ### 2.8 External API contract The bridge must isolate Konnaxion route details inside: ```text local_uckk\service\konnaxion_client ``` Minimum required operations: ```text health check list Smart Vote modalities create or resolve Smart Vote target create or resolve integration mapping submit proxy vote when enabled fetch Smart Vote result fetch EkoH weight metadata when authorized fetch anomaly/result metadata when authorized fetch source version where available ``` Expected adapter methods: ```text healthcheck() get_vote_modalities() create_target($target) create_integration_mapping($mapping) get_integration_mapping($targettype, $targetid) submit_vote($target, $vote) get_vote_result($targettype, $targetid) get_user_weight_summary($konnaxionuserid, $domain) get_result_metadata($targettype, $targetid) ``` Canonical service names: ```text SERVICE_CREATE_KONNAXION_MAPPING = local_uckk_create_konnaxion_mapping SERVICE_GET_KONNAXION_MAPPING = local_uckk_get_konnaxion_mapping SERVICE_SYNC_KONNAXION = local_uckk_sync_konnaxion SERVICE_REQUEST_SMART_VOTE_READING = mod_uckkassembly_request_smart_vote_reading SERVICE_IMPORT_SMART_VOTE_SNAPSHOT = mod_uckkassembly_import_smart_vote_snapshot SERVICE_CONTEST_SMART_VOTE_SNAPSHOT = mod_uckkassembly_contest_smart_vote_snapshot SERVICE_GET_SMART_VOTE_REPORT = report_uckk_get_smart_vote_report ``` HTTP route examples may be documented in implementation notes, but code must not hard-code undocumented Konnaxion internals outside the client class. ### 2.9 Smart Vote workflow #### 2.9.1 Preparation ```text 1. Assembly enters a state where Smart Vote readings are allowed. 2. Authorized user requests Smart Vote through CAP_REQUEST_SMART_VOTE. 3. Moodle checks login, context, capability, Assembly type, Assembly state, and integrity status. 4. local_uckk resolves identity and object mapping requirements. 5. local_uckk creates or resolves the Konnaxion target and IntegrationMapping. 6. mod_uckkassembly records EVENT_SMART_VOTE_READING_REQUESTED. 7. mod_uckkassembly stores target status using SMART_VOTE_TARGET_STATUS_ENUM. ``` #### 2.9.2 Vote collection modes Allowed modes: ```text proxy_vote_from_moodle external_vote_portal ``` `proxy_vote_from_moodle` means Moodle collects the participant's vote intent after Moodle session, context, eligibility, and capability checks, then sends it to Konnaxion. `external_vote_portal` means Moodle links the participant to Konnaxion, then imports only verified result snapshots. Both modes require: ```text identity mapping participant notice visibility rule capability check audit event privacy-provider coverage retention policy contestation path ``` #### 2.9.3 Result import ```text 1. Authorized user requests import, or a scheduled task imports after the voting window closes. 2. local_uckk fetches VoteResult and VoteModality metadata. 3. mod_uckkassembly validates target type, target id, modality, context, Assembly state, and mapping status. 4. mod_uckkassembly stores a Smart Vote snapshot in TABLE_SMART_VOTE_SNAPSHOT. 5. mod_uckkassembly stores audit trail in TABLE_SMART_VOTE_RESULT_AUDIT. 6. mod_uckkassembly displays the result as SV_COMPUTED_READING, not as SV_HUMAN_DECISION. 7. mod_uckkassembly records EVENT_SMART_VOTE_SNAPSHOT_IMPORTED. ``` Result import must reject: ```text target mismatch context mismatch modality mismatch stale result when refresh is required mapping conflict unresolved integrity block malformed payload missing quorum metadata when quorum is required unexpected raw voter identity exposure unknown source version when source version is required missing reading method missing provenance hash when archive snapshot is required ``` #### 2.9.4 Decision publication A final Assembly decision using Smart Vote must include: ```text motion reference Smart Vote modality raw vote count where available weighted reading quorum summary integrity/anomaly warnings human/institutional reasoning minority report when present contestation path archive snapshot reference source version provenance hash ``` Smart Vote must never call the final decision publication service by itself. Final decision publication must remain under: ```text ASSEMBLY_AUTHORITY = human_institutional_decision ``` ### 2.10 Failure and safety rules | Situation | Required Moodle behavior | |---|---| | Konnaxion disabled | Hide Smart Vote start actions; preserve existing non-Smart-Vote Assembly workflows. | | Konnaxion unavailable | Fail closed for Smart Vote import; do not fabricate, cache-as-final, or silently accept results. | | Identity unmapped | Deny Smart Vote action or permit only configured unweighted local fallback. | | Object mapping conflict | Pause Smart Vote reading and require authorized mapping review. | | Target mismatch | Reject import and open or offer integrity review. | | Stale result | Warn and require authorized refresh before decision publication. | | Anomaly detected | Mark reading as restricted/contested and route to integrity review if configured. | | Raw voter identities returned unexpectedly | Redact from display and archive; create privacy/integrity warning. | | API secret missing | Disable bridge and show admin-only configuration error. | | Payload validation fails | Reject payload, log metadata, and preserve audit event. | | Timeout | Fail closed, log metadata, keep prior accepted reading non-final, and do not update snapshot. | | Duplicate callback or retry | Use idempotency key and do not duplicate snapshot, audit row, or event. | | Mapping revoked | Stop imports and require remapping before new Smart Vote actions. | | Source version changed | Import only as new snapshot or supersession; never silently overwrite existing snapshot. | ### 2.11 Connected-mode classes, tasks, and events These classes, tasks, and events are required for the connected profile. They must not block `standalone_core` installation when the Konnaxion bridge is disabled and the connected profile is not claimed as enabled. `local_uckk` must deliver for `connected_konnaxion`: ```text local/uckk/classes/service/konnaxion_client.php local/uckk/classes/service/konnaxion_identity_mapper.php local/uckk/classes/service/konnaxion_object_mapper.php local/uckk/classes/service/konnaxion_sync_service.php local/uckk/classes/service/smartvote_bridge.php local/uckk/classes/service/smartvote_result_validator.php local/uckk/classes/external/create_konnaxion_mapping.php local/uckk/classes/external/get_konnaxion_mapping.php local/uckk/classes/external/sync_konnaxion.php local/uckk/classes/external/get_konnaxion_status.php local/uckk/classes/event/konnaxion_mapping_created.php local/uckk/classes/event/konnaxion_sync_completed.php local/uckk/classes/event/konnaxion_request_failed.php local/uckk/classes/event/konnaxion_mapping_revoked.php local/uckk/classes/task/sync_konnaxion_mappings.php ``` `mod_uckkassembly` must deliver for `connected_konnaxion`: ```text mod/uckkassembly/classes/local/smartvote_reading.php mod/uckkassembly/classes/local/smartvote_snapshot_repository.php mod/uckkassembly/classes/local/smartvote_target_repository.php mod/uckkassembly/classes/local/smartvote_audit_repository.php mod/uckkassembly/classes/external/request_smart_vote_reading.php mod/uckkassembly/classes/external/import_smart_vote_snapshot.php mod/uckkassembly/classes/external/contest_smart_vote_snapshot.php mod/uckkassembly/classes/event/smart_vote_reading_requested.php mod/uckkassembly/classes/event/smart_vote_snapshot_imported.php mod/uckkassembly/classes/event/smart_vote_snapshot_contested.php mod/uckkassembly/classes/event/smart_vote_snapshot_archived.php ``` `mod_uckkarchive` must deliver for `connected_konnaxion`: ```text mod/uckkarchive/classes/local/smartvote_archive_package.php mod/uckkarchive/classes/local/smartvote_snapshot_exporter.php mod/uckkarchive/classes/event/smart_vote_archive_package_created.php ``` `tool_uckkintegrity` must deliver for `connected_konnaxion`: ```text admin/tool/uckkintegrity/classes/local/smartvote_integrity_review.php admin/tool/uckkintegrity/classes/local/smartvote_anomaly_case.php admin/tool/uckkintegrity/classes/event/smartvote_anomaly_review_opened.php admin/tool/uckkintegrity/classes/event/smartvote_reading_invalidated.php ``` `report_uckk` must deliver for `connected_konnaxion`: ```text report/uckk/classes/external/get_smart_vote_report.php report/uckk/classes/local/smartvote_report_repository.php report/uckk/classes/local/smartvote_exporter.php report/uckk/classes/table/smartvote_report_table.php ``` Canonical events must match the canonical event variables: ```text EVENT_KONNAXION_MAPPING_CREATED EVENT_KONNAXION_SYNC_COMPLETED EVENT_SMART_VOTE_READING_REQUESTED EVENT_SMART_VOTE_SNAPSHOT_IMPORTED EVENT_SMART_VOTE_SNAPSHOT_CONTESTED EVENT_SMART_VOTE_SNAPSHOT_ARCHIVED ``` ### 2.12 Privacy, logging, and retention Konnaxion-related data may include: ```text Moodle userid Konnaxion external identifier pseudonymous identifier vote participation metadata Smart Vote reading expertise weight ethics score raw vote counts anomaly metadata source version provenance hash sync log metadata administrator action logs ``` The privacy provider of each storing plugin must cover: ```text metadata declaration user data export delete or anonymise behavior retention expiry restricted export where needed archive retention exception where required redaction behavior test coverage ``` Secrets must never be stored in logs, reports, events, archive packages, AI prompts, or AI responses. Archive snapshots must preserve: ```text SV_RAW_DATA when allowed SV_READING_METHOD SV_COMPUTED_READING SV_EXPERTISE_WEIGHT where used and exportable SV_HUMAN_DECISION when linked SV_MINORITY_REPORT when present SV_INTEGRITY_WARNING when present SV_CONTESTATION_STATUS SV_ARCHIVE_ITEM_ID sourceversion provenancehash ``` Retention must distinguish: | Data class | Default posture | |---|---| | API secrets | Secure config only; never exported in reports or archives. | | Sync metadata | Retain according to `konnaxion_retention_days`. | | Payload logs | Disabled by default; strict retention and restricted visibility if enabled. | | Identity mappings | Export/delete/anonymise according to user privacy policy and institutional record needs. | | Object mappings | Retain while linked Moodle object exists; archive or invalidate when object is archived. | | Smart Vote snapshots | Retain as institutional record when used in Assembly decision, subject to redaction rules. | | Integrity warnings | Retain under integrity-case retention rules. | | Archive packages | Retain according to archive visibility and institutional retention rules. | ### 2.13 Connected-mode Konnaxion acceptance gate A `connected_konnaxion` release candidate fails this gate if any of these are true: ```text Konnaxion writes directly into Moodle source tables. Konnaxion identity/object mapping tables are missing. Smart Vote snapshots are missing. Smart Vote result audit table is missing. Smart Vote appears as an automatic final decision. Final Assembly decisions can be published without Moodle capability checks. Smart Vote result import does not validate target, context, modality, state, and mapping. Smart Vote result import overwrites earlier snapshots without audit trail. Konnaxion API secrets appear in logs, reports, archives, events, AI prompts, or exports. Payload logging has no privacy-provider coverage. Konnaxion outage fabricates or silently accepts results. Timeout, retry, failure, and idempotency behavior is untested. Capability names do not match the canonical capability variables. Service names do not match the canonical service variables. Event names do not match the canonical event variables. Status values do not match the canonical state variables. ``` ## 3. AI integration ### 3.1 Component AI integration is owned by: ```text aiprovider_uckk ``` AI may also be consumed by: ```text local_uckk mod_uckkchallenge mod_uckkassembly mod_uckkarchive tool_uckkintegrity report_uckk ``` AI integration must follow Moodle AI provider conventions and UCKK non-sovereignty rules. ### 3.2 AI roles AI may support: ```text summarisation translation evidence clarification course outline drafting challenge hint generation archive description drafting integrity uncertainty detection report explanation Smart Vote result explanation Konnaxion metadata summarisation ``` AI must not perform: ```text final grading final badge award final competency certification final Assembly decision final integrity judgment silent evidence validation silent archive validation secret-bearing prompt construction Smart Vote result mutation Konnaxion mapping mutation without service checks ``` ### 3.3 AI actions Allowed AI actions must be explicitly declared. Each AI action must define: ```text action name originating component context required capability input data categories output data categories retention rule redaction rule human review requirement event logging privacy-provider coverage ``` AI outputs that summarize Smart Vote or Konnaxion data must label themselves as explanations, not decisions. ### 3.4 AI logging settings The AI provider must define settings for: ```text enable_ai_provider ai_default_model ai_request_timeout_seconds ai_log_prompts ai_log_responses ai_redact_personal_data ai_redact_konnaxion_secrets ai_require_human_review ai_retention_days ``` Prompt and response logging must be disabled by default unless governance explicitly enables it. If logs are retained, privacy providers must implement export and deletion/anonymisation behavior. ### 3.5 AI output label Every AI-assisted output must include a visible or machine-readable label: ```text AI-assisted draft. Not a final institutional decision. ``` When AI summarizes Smart Vote: ```text AI-assisted explanation of a Smart Vote reading. Not a final Assembly decision. ``` When AI summarizes integrity or anomaly metadata: ```text AI-assisted integrity summary. Not a final integrity judgment. ``` ### 3.6 AI audit requirements AI actions must emit events or logs sufficient to answer: ```text who requested the action what component requested it which context it belonged to what data categories were sent whether personal data was redacted whether Konnaxion data was included whether Smart Vote data was included what output was produced or retained who reviewed or accepted the output ``` AI logs must not contain Konnaxion API secrets, hidden payload secrets, or unredacted data where redaction is configured. ## 4. Reporting ### 4.1 `report_uckk` `report_uckk` owns core institutional reporting. In `connected_konnaxion`, it also owns Smart Vote and Konnaxion-derived reports. Reports must be read-only unless a specific export or acknowledgement workflow is explicitly declared. Core required reports: ```text campus overview program/pathway progress challenge participation challenge validation Assembly activity Assembly decisions archive inventory archive provenance integrity cases badge and competency recognition seed execution history AI usage audit privacy/export readiness release acceptance evidence ``` Connected-mode reports, required only when `connected_konnaxion` is enabled, packaged, or claimed as supported: ```text Smart Vote readings Smart Vote contestations Smart Vote archive coverage Konnaxion bridge status Konnaxion sync history Konnaxion mapping conflicts Konnaxion failure/retry history ``` ### 4.2 Report filters Reports must support relevant filters: ```text date range course category cohort role pathway program activity module Assembly motion decision status Smart Vote snapshot status Smart Vote contestation status Konnaxion mapping status Konnaxion sync status integrity status archive visibility privacy-retention class ``` Every report must enforce Moodle capabilities and contexts. Smart Vote and Konnaxion filters apply only when the connected profile is enabled and the report includes connected-mode data. Report visibility must use: ```text CAP_VIEW_SMART_VOTE_REPORTS = report/uckk:viewsmartvotereports ``` where the report includes Smart Vote data in `connected_konnaxion`. ### 4.3 Export Export formats: ```text CSV JSON PDF when supported by Moodle stack archive package manifest release acceptance manifest ``` Exports must include: ```text export title export generator export timestamp Moodle site identifier source filters viewer userid data provenance privacy warning where needed Konnaxion source version where applicable Smart Vote snapshot id where applicable archive item id where applicable ``` Smart Vote exports must distinguish: ```text SV_RAW_DATA SV_READING_METHOD SV_COMPUTED_READING SV_HUMAN_DECISION SV_MINORITY_REPORT SV_INTEGRITY_WARNING SV_CONTESTATION_STATUS SV_ARCHIVE_ITEM_ID ``` Reports and exports must not collapse Smart Vote readings into final decisions. ### 4.4 Report implementation contract `report_uckk` must deliver for `standalone_core`: ```text report/uckk/index.php report/uckk/settings.php report/uckk/db/access.php report/uckk/db/services.php when core external services are declared report/uckk/classes/local/report_repository.php report/uckk/classes/local/exporter.php report/uckk/classes/table/* when table renderers are used report/uckk/classes/output/* when output renderers are used report/uckk/classes/privacy/provider.php report/uckk/lang/en/report_uckk.php report/uckk/lang/fr/report_uckk.php report/uckk/tests/ report/uckk/tests/behat/ ``` `report_uckk` must additionally deliver for `connected_konnaxion`: ```text report/uckk/classes/external/get_smart_vote_report.php report/uckk/classes/local/smartvote_report_repository.php report/uckk/classes/local/smartvote_exporter.php report/uckk/classes/table/smartvote_report_table.php connected-mode PHPUnit coverage connected-mode Behat coverage ``` ### 4.5 Report/export registry All report and export definitions must be represented in: ```text PRESET_EXPORTS = presets/exports.json ``` The export registry must include: ```text report key export key owning component source tables source services required capability context rule privacy class retention class supported formats test fixture acceptance evidence requirement ``` ## 5. Seed execution ### 5.1 `tool_uckkseed` modes `tool_uckkseed` must support: ```text dry_run apply verify rollback_plan ``` Seed execution must be idempotent. Repeated execution must not duplicate: ```text categories courses cohorts roles capabilities competencies badges reports navigation records state machines events Konnaxion mapping defaults when connected-mode presets are enabled privacy-retention rules export definitions ``` ### 5.2 Seed input files Core required seed input files: ```text presets/categories.json presets/courses.json presets/cohorts.json presets/roles.json PRESET_CAPABILITIES = presets/capabilities.json presets/competencies.json presets/badges.json presets/reports.json presets/navigation.json PRESET_STATE_MACHINES = presets/state_machines.json PRESET_EVENTS = presets/events.json PRESET_PRIVACY_RETENTION = presets/privacy_retention.json PRESET_EXPORTS = presets/exports.json ``` Connected-mode seed input file: ```text PRESET_KONNAXION_MAPPINGS = presets/konnaxion_mappings.json ``` The connected-mode seed file is required only when the `connected_konnaxion` profile is enabled, packaged, or claimed as supported. Each JSON file must have: ```text schema version stable keys idempotent lookup keys validation rules owner component test fixture coverage ``` ### 5.3 Idempotency rule Seed operations must use stable lookup keys. Examples: ```text course shortname category idnumber cohort idnumber role shortname capability name competency idnumber badge unique key report key navigation key state-machine key event key Konnaxion mapping key export key privacy-retention key ``` Seed logs must report: ```text created updated unchanged skipped failed ``` ### 5.4 Seed log `tool_uckkseed` must store seed execution logs with: ```text mode actor userid timestamp preset file preset version operation count created count updated count unchanged count skipped count failed count error summary ``` Logs that include personal data must be privacy-covered. Connected-mode Konnaxion seed defaults must never store API secrets. ### 5.5 Seed safety requirements Seed apply must not run without: ```text sesskey admin capability valid JSON schema validation dependency verification dry-run summary available confirmation step ``` Seed rollback must produce a plan, not blindly delete institutional records. ## 6. Implementation-readiness gate Before a release candidate may be installed in Moodle, it must pass all readiness checks in this section. ### 6.1 Filetype correctness Every file must contain code appropriate to its extension. ```text .php files must start with requires->js_call_amd(...)` is a cleanup warning, not an install blocker by itself. Executable PHP/page-controller code inside `.js` remains a blocker. Blocking defects: ```text Markdown fences inside PHP source files Executable PHP/page-controller code inside amd/src JavaScript files JavaScript module code inside PHP page files raw implementation instructions inside executable files missing opening theme_uckk course/format/uckk => format_uckk local/uckk => local_uckk blocks/uckk_dashboard => block_uckk_dashboard mod/uckkchallenge => mod_uckkchallenge mod/uckkassembly => mod_uckkassembly mod/uckkarchive => mod_uckkarchive admin/tool/uckkseed => tool_uckkseed admin/tool/uckkintegrity => tool_uckkintegrity report/uckk => report_uckk ai/provider/uckk => aiprovider_uckk ``` The following must agree with the component: ```text version.php @package language component names capability prefixes service component names event namespaces AMD module names template names test namespaces privacy provider namespaces ``` ### 6.3 Required class layer Any referenced namespaced class must have a matching file under `classes/`. Required class families, where applicable: ```text classes/form/* classes/event/* classes/external/* classes/output/* classes/table/* classes/task/* classes/local/* classes/service/* classes/privacy/provider.php ``` External services declared in `db/services.php` must map to real `classes/external/*` classes. Scheduled tasks declared in `db/tasks.php` must map to real `classes/task/*` classes. Events declared, triggered, or listed in `db/events.php` must map to real `classes/event/*` classes. Forms referenced by pages must map to real `classes/form/*` classes or valid legacy form files. ### 6.4 Privacy provider coverage Every plugin storing, displaying, exporting, logging, or deriving personal data must include a privacy provider. Minimum expected privacy providers: ```text local_uckk mod_uckkarchive mod_uckkassembly mod_uckkchallenge tool_uckkseed tool_uckkintegrity block_uckk_dashboard format_uckk report_uckk aiprovider_uckk ``` When `connected_konnaxion` is enabled, Konnaxion-related data stored by `local_uckk`, `mod_uckkassembly`, `mod_uckkarchive`, `tool_uckkintegrity`, or `report_uckk` must be included in those plugins' privacy providers. Each provider must define: ```text metadata declaration export behavior delete behavior anonymisation behavior retention behavior redaction behavior archive-retention exception where needed ``` ### 6.5 Page and service access checks Every user-facing page, admin page, AJAX entry point, external service, report, export, and file-serving path must define: ```text require_login behavior context resolution required capability sesskey requirement for writes parameter validation output escaping redirect/error behavior privacy impact events emitted ``` Write operations must not be possible by GET request alone. ### 6.6 Canonical variable alignment gate The implementation is not ready until all canonical variables in this document are resolved across docs, presets, code, tests, and release artifacts. Core blocking defects: ```text active docs still point to LEGACY_DOC_10 as the correction target outside DOC_11 or migration notes active docs still point to obsolete or missing DOC_10 filenames instead of the canonical DOC_10 outside DOC_11 or migration notes core preset files are missing from seed input core report/export definitions are missing from PRESET_EXPORTS privacy/retention definitions are missing from PRESET_PRIVACY_RETENTION status values for core workflows do not match canonical state variables ``` Connected-mode blocking defects, when `connected_konnaxion` is enabled or claimed as supported: ```text Konnaxion capabilities do not match CAP_* variables Konnaxion services do not match SERVICE_* variables Konnaxion events do not match EVENT_* variables Konnaxion tables do not match TABLE_* variables Smart Vote fields do not match SV_* variables Smart Vote/Konnaxion status values do not match *_STATUS_ENUM variables PRESET_KONNAXION_MAPPINGS is missing when connected-mode presets are enabled ``` ## 7. Static validation commands A release candidate must pass these checks before installation in Moodle: ```bash # PHP syntax. find . -name '*.php' -not -path './vendor/*' -print0 | xargs -0 -n1 php -l # Accidental Markdown fences in PHP. grep -RIn --include='*.php' '```' . # Accidental executable PHP/page-controller code in JavaScript. # This is a blocking check. It intentionally does not fail on a plain comment that only mentions $PAGE. grep -RIn --include='*.js' 'requires->js_call_amd' . || true # JSON syntax. find . -name '*.json' -print0 | xargs -0 -n1 python3 -m json.tool >/dev/null # XML syntax. find . -name 'install.xml' -print0 | xargs -0 -n1 xmllint --noout # Canonical variable drift checks. # Deprecated names are allowed only inside DOC_11, explicit migration notes, or deprecated-alias tables. grep -RIn '10_implementation_correction_plan.md\|konnaxion_alignment_and_correction_plan.md\|OPTIONAL_KONNAXION_CONTRACT' docs/ presets/ release/ | grep -v 'docs/11_cross_doc_alignment_registry.md' | grep -v 'deprecated' | grep -v 'migration' || true grep -RIn 'configurekonnaxion\|usesmartvote\|viewsmarkvotereading\|viewsmartvotereading\|importsmartvoteresult\|exportsmartvotesnapshot\|contestsmartvotereading' docs/ presets/ plugins/ | grep -v 'docs/11_cross_doc_alignment_registry.md' | grep -v 'deprecated' | grep -v 'migration' || true ``` Project validation scripts may wrap these commands, but they must not replace them unless they provide equivalent coverage. The grep checks above are drift detectors. They should return no active canonical references unless the match appears only inside `DOC_11`, an explicit migration note, or a deprecated-alias table. ## 8. Installation Final standalone installation must support: ```text copy plugin suite into Moodle plugin paths run Moodle upgrade purge Moodle caches enable theme_uckk configure local_uckk run tool_uckkseed dry_run run tool_uckkseed apply verify state-machine presets verify event presets verify privacy-retention presets verify export presets verify reports verify dashboard verify privacy checks run automated tests ``` Connected-mode installation additionally verifies: ```text configure Konnaxion bridge disabled by default verify Konnaxion mapping presets verify Konnaxion bridge settings verify Konnaxion health-check safe failure when unconfigured verify Smart Vote actions are hidden unless enabled and authorized ``` Installation must be tested first on a clean disposable Moodle target. ### 8.1 Installation gate A clean standalone target must pass: ```text Moodle detects all plugins with correct component names. Moodle upgrade completes without fatal error. All install.xml files create expected core tables. All upgrade.php files are syntactically valid and idempotent. All declared core dependencies are present or documented. All core capabilities appear under the correct component. All scheduled tasks appear under the correct component. All web service functions load their declared classes. All privacy providers are discoverable. Konnaxion bridge is disabled by default when present. Smart Vote actions are hidden unless connected mode is enabled and authorized. ``` A connected-mode target must additionally pass: ```text All Konnaxion and Smart Vote tables use canonical table names. All canonical Konnaxion/Smart Vote capabilities exist. All canonical Konnaxion/Smart Vote services exist. All canonical Konnaxion/Smart Vote events exist. Konnaxion health check fails safely when unconfigured. Konnaxion bridge remains disabled by default unless explicitly configured. ``` ## 9. Upgrade Every plugin must include: ```text version.php db/upgrade.php when schema changes upgrade notes backward-compatible table changes data migration tests ``` Breaking changes require: ```text migration plan rollback plan administrator notice data backup recommendation Konnaxion mapping preservation plan when connected-mode data exists Smart Vote snapshot preservation plan when connected-mode data exists privacy/retention impact note ``` Upgrade code must not duplicate: ```text tables roles capabilities scheduled tasks seed records admin settings Konnaxion mappings Smart Vote snapshots event registry rows export registry rows ``` ## 10. Testing ### 10.1 PHPUnit Core PHPUnit coverage must pass without Konnaxion. Connected-mode PHPUnit coverage is required when `connected_konnaxion` is enabled, packaged, or claimed as supported. Core PHPUnit coverage: ```text local_uckk services pathway assignment provenance service challenge state transitions Assembly state transitions without Smart Vote archive versioning without Smart Vote snapshots integrity case transitions without Konnaxion-derived records privacy export/delete for core UCKK records seed idempotency for core presets report query builders for core reports AI request redaction external service parameter validation for declared core services capability failure paths for core capabilities event creation for declared core events scheduled task execution for declared core tasks canonical variable resolution for standalone_core ``` Connected-mode PHPUnit coverage, required only when `connected_konnaxion` is enabled, packaged, or claimed as supported: ```text Konnaxion client failure handling Konnaxion identity mapping Konnaxion object mapping Konnaxion sync log Konnaxion retry and idempotency Konnaxion timeout behavior Konnaxion source-version preservation Smart Vote target mapping Smart Vote result validation Smart Vote snapshot storage Smart Vote result audit Smart Vote archive export Smart Vote anomaly handling Smart Vote contestation Smart Vote report export canonical variable resolution for connected_konnaxion ``` Recommended command pattern: ```bash php admin/tool/phpunit/cli/init.php vendor/bin/phpunit local/uckk/tests vendor/bin/phpunit mod/uckkarchive/tests vendor/bin/phpunit mod/uckkassembly/tests vendor/bin/phpunit mod/uckkchallenge/tests vendor/bin/phpunit admin/tool/uckkseed/tests vendor/bin/phpunit admin/tool/uckkintegrity/tests vendor/bin/phpunit blocks/uckk_dashboard/tests vendor/bin/phpunit course/format/uckk/tests vendor/bin/phpunit report/uckk/tests vendor/bin/phpunit ai/provider/uckk/tests ``` ### 10.2 Behat Core Behat workflows must pass without Konnaxion. Connected-mode Behat workflows are required when `connected_konnaxion` is enabled, packaged, or claimed as supported. Required end-to-end workflows by profile: ```text install seed and view campus Joueur completes UCKK-000 Joueur submits challenge proof Mentor evaluates challenge Inquisiteur opens and closes case Assembly publishes decision Decision is contested and archived Archiviste validates archive item Badge is awarded after evidence validation Report is viewed by Gestionnaire AI summary is generated with non-authority warning Konnaxion bridge health check is performed by authorized admin Konnaxion bridge health check fails safely when unconfigured Assembly Smart Vote reading is started by authorized user Smart Vote result is imported as reading, not final decision Smart Vote reading is contested and routed to integrity review Smart Vote snapshot is archived with provenance Smart Vote report is visible only through CAP_VIEW_SMART_VOTE_REPORTS Privacy export includes UCKK and Konnaxion mapping records Konnaxion outage does not publish a final decision Canonical capability names appear in role setup ``` Recommended command pattern: ```bash php admin/tool/behat/cli/init.php php admin/tool/behat/cli/run.php --tags='@uckk' ``` ### 10.3 JavaScript build All AMD source files must build successfully. ```bash npx grunt amd ``` AMD source files must remain source-only JavaScript files. Generated build artifacts must match Moodle build expectations and must not contain PHP controller code. ### 10.4 Manual smoke tests Manual standalone smoke tests must pass without Konnaxion. Connected-mode smoke tests are required when `connected_konnaxion` is enabled, packaged, or claimed as supported. Manual standalone smoke tests must verify: ```text plugin installation page shows no missing dependencies front page loads under theme_uckk course using format_uckk loads Joueur dashboard block loads archive activity view loads challenge activity view loads Assembly activity view loads without Smart Vote integrity admin index loads seed admin page loads report index loads AI provider settings page loads privacy registry detects UCKK providers Konnaxion bridge absence or disabled state does not break standalone workflows ``` Manual connected-mode smoke tests, required only when `connected_konnaxion` is enabled, packaged, or claimed as supported: ```text Konnaxion bridge settings page loads Konnaxion bridge disabled state is safe Konnaxion health check fails safely when unconfigured Assembly Smart Vote panel loads only for authorized users report_uckk Smart Vote report loads only for authorized users Konnaxion identity/object mapping screens require capability Smart Vote import cannot publish final decision Smart Vote archive package includes provenance ``` ## 11. Release package Final release contains: ```text plugins/ presets/ docs/ tests/ release/installation.md release/upgrade.md release/rollback.md release/acceptance-checklist.md CHANGELOG.md LICENSE.md README.md ``` ### 11.1 Release manifest The release package must include a manifest listing: ```text release version Moodle version target plugin paths plugin components plugin versions required dependencies preset files build commands used test commands used test results summary known limitations canonical variable resolution summary Konnaxion bridge enabled/disabled default state when connected profile is included Konnaxion API contract version tested when connected profile is included Smart Vote modalities tested when connected profile is included external integration test results when connected profile is included privacy/retention test results report/export test results ``` ### 11.2 Canonical variable manifest The release package must include a canonical variable manifest proving that: ```text DOC_10 is 10_konnaxion_smart_vote_integration_contract.md LEGACY_DOC_10 is not the active target implemented standalone capability variables match db/access.php and presets/capabilities.json implemented standalone service variables match db/services.php and classes/external implemented standalone event variables match classes/event and presets/events.json implemented standalone table variables match db/install.xml and DOC_04 connected-mode CAP_*, SERVICE_*, EVENT_*, TABLE_*, SV_*, and *_STATUS_ENUM variables are either implemented and tested, or explicitly marked as connected_konnaxion deferred in DOC_11 and the gap report PRESET_* variables required for the claimed profile exist and validate as JSON ``` ## 12. Acceptance checklist ### 12.1 Core standalone acceptance checklist ```text [ ] PHP syntax check passes across all PHP files. [ ] No Markdown fences remain inside PHP source files. [ ] No PHP controller code exists inside amd/src JavaScript files. [ ] No JavaScript module body is misplaced inside a PHP page file. [ ] Every version.php component matches its plugin path. [ ] Every declared core service class exists under classes/external. [ ] Every declared core task class exists under classes/task. [ ] Every triggered core event class exists under classes/event. [ ] Every referenced form class exists. [ ] Every plugin that handles personal data has a privacy provider. [ ] Clean Moodle target installs all core plugins with Konnaxion disabled or unconfigured. [ ] All plugins show stable maturity metadata. [ ] Moodle upgrade completes without error. [ ] UCKK theme applies successfully. [ ] Seed dry-run produces expected standalone plan. [ ] Seed apply creates all core campus objects. [ ] Seed input includes capabilities, state machines, events, privacy retention, and exports. [ ] UCKK-000 and TC101–TC108 exist and use format_uckk. [ ] Roles and capabilities are applied. [ ] Canonical capability variables match db/access.php and presets/capabilities.json for core workflows. [ ] Joueur dashboard works. [ ] Challenge workflow works. [ ] Assembly workflow works without Smart Vote enabled. [ ] Archive workflow works without Smart Vote snapshots. [ ] Integrity workflow works without Konnaxion-derived records. [ ] AI provider can be configured and disabled. [ ] AI outputs are labelled non-authoritative. [ ] Reports are visible only to authorized users. [ ] Core report/export definitions exist in presets/exports.json. [ ] Privacy export/delete works for core UCKK records. [ ] Privacy/retention definitions exist in presets/privacy_retention.json. [ ] JavaScript AMD build passes. [ ] Behat suite passes for core workflows. [ ] PHPUnit suite passes for core workflows. [ ] No UCKK accreditation confusion appears in public UI. [ ] UCKK / kOA / kOA Digital Ecosystem / King Klown / Konnaxion boundary is preserved. [ ] Konnaxion is not required for standalone installation, seed execution, Assembly decisions, Archive preservation, Integrity review, reporting, privacy export/delete, or tests. ``` ### 12.2 Optional Konnaxion-connected acceptance checklist This checklist is required only when `connected_konnaxion` is enabled, packaged, or claimed as supported. ```text [ ] Konnaxion bridge can be configured and disabled. [ ] Konnaxion bridge is disabled safely by default. [ ] Konnaxion health check works without exposing secrets. [ ] Konnaxion health check fails safely when unconfigured. [ ] Konnaxion identity/object mappings use canonical table names. [ ] Konnaxion sync logs use canonical sync status values. [ ] Konnaxion services use canonical service names. [ ] Konnaxion events use canonical event names. [ ] PRESET_KONNAXION_MAPPINGS exists and validates when connected-mode presets are enabled. [ ] Smart Vote can be started only by authorized Assembly users. [ ] Smart Vote actions are hidden unless enabled and authorized. [ ] Smart Vote target mapping uses canonical target status values. [ ] Smart Vote result import validates target, context, modality, state, and mapping. [ ] Smart Vote result appears as a reading, not an automatic final decision. [ ] Smart Vote snapshot stores raw data, reading method, computed reading, provenance, visibility, and contestation status. [ ] Smart Vote snapshot archives method, result, provenance, visibility, and contestation path. [ ] Smart Vote result audit records review, correction, contestation, and supersession. [ ] Konnaxion outage fails safely. [ ] Konnaxion timeout, retry, failure, and idempotency behavior is tested. [ ] Konnaxion identity/object mappings are privacy-covered. [ ] AI outputs involving Smart Vote are labelled non-authoritative. [ ] Smart Vote reports use CAP_VIEW_SMART_VOTE_REPORTS. [ ] Smart Vote reports and exports preserve provenance, reading method, contestation state, and privacy filtering. [ ] Privacy export/delete covers Konnaxion mappings, Smart Vote snapshots, sync logs, and connected-mode user references where stored. [ ] Smart Vote does not replace Assembly sovereignty. [ ] Archives preserve Smart Vote snapshots and Assembly decisions separately, with provenance and contestability. ``` ## 13. Final delivery statement The core implementation is accepted when UCKK-Moodle can be installed from a clean target and used immediately as the standalone campus for UCKK, with institutional, academic, symbolic, integrity, archive, AI, reporting, delivery, privacy, and governance structures present and functional without requiring Konnaxion. The Konnaxion-connected profile is accepted separately when the Konnaxion bridge, Smart Vote reading workflow, connected-mode reports, sync/mapping behavior, privacy coverage, archive preservation, failure handling, PHPUnit coverage, Behat coverage, and release evidence pass the connected-mode gates. A code dump that contains scaffold files but fails filetype correctness, Moodle component correctness, class-layer discovery, privacy-provider discovery, canonical variable resolution, Moodle upgrade, JavaScript build, PHPUnit, or Behat for the claimed profile is not a final delivery. It is a correction candidate. Konnaxion may compute Smart Vote readings. UCKK-Moodle Assemblées decide. Archives preserve both, with provenance and contestability. ================================================================================================ FILE: docs/10_konnaxion_smart_vote_integration_contract.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: a225c829371fe4083b7b86aecc3512319fad0326d3583d5180e9d7dd19ca163b CONTENT_BYTES: 31215 ================================================================================================ # 10 — Konnaxion Smart Vote Integration Contract **Status:** Optional connected-mode integration contract **Target systems:** UCKK-Moodle + Konnaxion v14 **Purpose:** Define how UCKK-Moodle can connect to Konnaxion Smart Vote without making Konnaxion a core dependency and without weakening Moodle permissions, UCKK Assembly legitimacy, archive provenance, privacy, or integrity review. This document consumes `docs/11_cross_doc_alignment_registry.md` for shared variables, document paths, capability names, table names, operating modes, deprecated aliases, and standalone-vs-connected requirements. It must not redefine shared variables locally. ## 0. Operating profiles UCKK-Moodle has two supported operating profiles. | Profile | Meaning | Release rule | |---|---|---| | `standalone_core` | UCKK-Moodle operates without Konnaxion. | Must install, seed, teach, deliberate, archive, report, and enforce permissions without Konnaxion. | | `connected_konnaxion` | UCKK-Moodle enables the Konnaxion bridge for Smart Vote and EkoH/advisory readings. | Accepted only when the bridge, mappings, privacy rules, archive snapshots, reports, and failure handling pass connected-mode gates. | Core variables: ```text KONNAXION_REQUIRED_FOR_CORE = false SMART_VOTE_REQUIRED_FOR_CORE = false KONNAXION_DEFAULT_STATE = disabled SMART_VOTE_DEFAULT_STATE = disabled unless Konnaxion bridge is enabled ``` Konnaxion is an optional Layer 6 integration. It must never be a hard dependency for standalone installation, standalone seed execution, ordinary Assembly decisions, archive records, integrity workflows, or core reports. Current code-snapshot status: ```text standalone_core = implemented target for the next code revision connected_konnaxion = target connected-mode profile, not a current standalone-core blocker ``` Executable code must not be forced to create Konnaxion/Smart Vote classes, services, tables, presets, or reports unless the connected profile is explicitly implemented. ## 1. Governing rule ```text Konnaxion computes Smart Vote readings. UCKK-Moodle owns Assembly decisions. Archives preserve both, with provenance and contestability. ``` Smart Vote is a decision-support reading, not a sovereign decision-maker. It may inform an Assembly, but it must not automatically publish a decision, award a badge, validate a competency, close an integrity case, modify an archive item, or replace a human/procedural decision path. ## 2. Domain boundary | Domain | Responsibility | |---|---| | UCKK-Moodle | Campus authority for learning records, assemblies, decisions, archives, permissions, reports, privacy, and integrity review. | | Konnaxion | External collective-intelligence system providing EkoH reputation/advisory data, vote modalities, weighted vote aggregation, Smart Vote results, and analytics when connected mode is enabled. | | `local_uckk` | Core integration coordinator. In connected mode, Moodle-side Konnaxion bridge owner: settings, endpoint client, object mapping, user mapping, sync logs, and shared bridge services. | | `mod_uckkassembly` | Source of truth for Assembly motions, deliberation, decision state, minority reports, Smart Vote reading workflow, contestability, and minutes. | | `mod_uckkarchive` | Source of truth for archived snapshots, provenance, evidence, decision memory, and versioned records. | | `tool_uckkintegrity` | Source of truth for disputes, anomalies, procedural corrections, privacy concerns, and integrity review. | | `report_uckk` | Permission-aware reporting on UCKK-side records. In connected mode, also reports on imported Smart Vote snapshots. | Authority boundaries: ```text SMART_VOTE_AUTHORITY = computed_reading_only ASSEMBLY_AUTHORITY = human_institutional_decision ARCHIVE_AUTHORITY = provenance_and_contestation_memory PERMISSION_RULE = moodle_capabilities_remain_authoritative DIRECT_WRITE_RULE = external_systems_never_write_moodle_source_tables ``` ## 3. Architecture decision Do not add a new Moodle plugin for the first connected-mode integration pass. Use the existing UCKK distribution: ```text local_uckk -> optional Konnaxion bridge, endpoint client, identity mapper, object mapper, sync logs, configuration mod_uckkassembly -> Assembly workflow, optional Smart Vote reading panel, motion-to-target workflow, decision publication mod_uckkarchive -> immutable archive snapshots of Smart Vote readings and final decisions tool_uckkintegrity -> Smart Vote anomaly/dispute/correction workflow report_uckk -> read-only reports on Smart Vote readings, Assembly decisions, archive status, and integrity flags ``` A separate plugin such as `local_uckkkonnaxion` may be introduced only if the bridge becomes independently distributable. Until then, `local_uckk` is the correct owner because it already owns shared services, institutional registry, and cross-plugin coordination. Connected-mode services must degrade safely. If Konnaxion is disabled, unavailable, misconfigured, or unauthorized, UCKK-Moodle must continue to support non-Smart-Vote Assembly workflows. ## 4. Optional Moodle settings When connected mode is implemented, add these settings to `local_uckk/settings.php`: ```text enable_konnaxion_bridge konnaxion_base_url konnaxion_api_client_id konnaxion_api_secret konnaxion_api_timeout_seconds konnaxion_verify_tls konnaxion_fail_closed konnaxion_log_metadata konnaxion_log_payloads konnaxion_retention_days konnaxion_pseudonymize_user_ids smartvote_enabled smartvote_default_modality smartvote_allowed_assembly_types smartvote_require_archive_snapshot smartvote_require_integrity_review_on_anomaly smartvote_allow_proxy_vote_from_moodle smartvote_allow_external_vote_portal smartvote_import_requires_review smartvote_archive_on_decision_publish smartvote_max_result_age_seconds ``` Default values: ```text enable_konnaxion_bridge = false smartvote_enabled = false konnaxion_fail_closed = true konnaxion_log_payloads = false smartvote_import_requires_review = true smartvote_archive_on_decision_publish = true ``` Security rules: ```text API secrets must use Moodle secure/password config handling. Secrets must never appear in reports, debug output, seed logs, archive exports, exception pages, events, AI prompts, or AI logs. Payload logging is disabled by default. If payload logging is enabled, privacy-provider export/deletion rules must cover it. ``` ## 5. Optional connected-mode Moodle capabilities Capabilities must use the canonical `CAP_*` variables from the root doctrine and roles/security registry. ### `local_uckk` The current code snapshot implements a generic integration-administration capability: ```text CAP_MANAGE_KONNAXION = local/uckk:manageintegrations CAP_MAP_KONNAXION_OBJECTS = local/uckk:manageintegrations CAP_VIEW_KONNAXION_LOGS = local/uckk:manageintegrations ``` Narrower Konnaxion capabilities may be introduced later only through a coordinated migration in `DOC_05`, `DOC_11`, `db/access.php`, presets, language strings, services/pages, PHPUnit tests, and Behat tests. Until then, this contract must not claim that `local/uckk:managekonnaxion`, `local/uckk:mapkonnaxionobjects`, or `local/uckk:viewkonnaxionlogs` are implemented executable capabilities. ### `mod_uckkassembly` These capabilities are target connected-mode capabilities. They must not be required for standalone-core Assembly workflows until implemented in `db/access.php`, presets, language strings, services/pages, PHPUnit tests, and Behat tests. ```text CAP_REQUEST_SMART_VOTE = mod/uckkassembly:requestsmartvote CAP_VIEW_SMART_VOTE = mod/uckkassembly:viewsmartvote CAP_REVIEW_SMART_VOTE = mod/uckkassembly:reviewsmartvote CAP_CONTEST_SMART_VOTE = mod/uckkassembly:contestsmartvote ``` ### `mod_uckkarchive` This is a target connected-mode capability. It must not be required for standalone-core Archive workflows until implemented. ```text CAP_ARCHIVE_SMART_VOTE = mod/uckkarchive:archivesmartvote ``` ### `report_uckk` This is a target connected-mode capability. It must not be required for standalone-core reports until implemented. ```text CAP_VIEW_SMART_VOTE_REPORTS = report/uckk:viewsmartvotereports ``` Do not use drifting, premature, or misspelled capability names as active values. These names may appear only in `DOC_11` deprecated-alias registry or explicit migration notes: ```text local/uckk:managekonnaxion local/uckk:configurekonnaxion local/uckk:managekonnaxionmappings local/uckk:mapkonnaxionobjects local/uckk:viewkonnaxionlogs local/uckk:viewkonnaxionstatus mod/uckkassembly:opensmartvote mod/uckkassembly:viewsmarkvotereading mod/uckkassembly:viewsmartvotereading mod/uckkassembly:usesmartvote mod/uckkassembly:importsmartvoteresult mod/uckkassembly:exportsmartvotetarget mod/uckkassembly:exportsmartvotesnapshot mod/uckkassembly:contestsmartvotereading mod/uckkarchive:viewsmartvotesnapshot mod/uckkarchive:archivesmartvotesnapshot report/uckk:viewsmartvote report/uckk:exportsmartvote report/uckk:viewkonnaxionlogs ``` The typo `mod/uckkassembly:viewsmarkvotereading` is explicitly banned. Naming note: keep the public UI label as **Smart Vote**, but use lowercase Moodle capability names with `smartvote` as one word. ## 6. Optional connected-mode data model additions These tables are part of `connected_konnaxion` mode. They are target connected-mode tables and must not be required for standalone UCKK-Moodle installation, upgrade, seed execution, tests, or operation until implemented in `DOC_04`, XMLDB, upgrade steps, privacy providers, presets, PHPUnit, and Behat. ### 6.1 `local_uckk_kx_user_map` Owner: `local_uckk` Purpose: Map Moodle users/Joueurs to Konnaxion identities without exposing unnecessary external personal data. | Field | Purpose | |---|---| | `id` | Primary key | | `userid` | Moodle user id | | `externalid` | Konnaxion user id or stable pseudonymous id | | `externaltype` | Konnaxion object type, normally `user` | | `externalhash` | Hash used for reports/exports when raw external id should not be exposed | | `mappingstatus` | `draft`, `active`, `suspended`, `superseded`, `archived`, `invalidated` | | `verifiedby` | Moodle user id that verified the map | | `timeverified` | Verification timestamp | | `sourceversion` | Konnaxion source version/revision/timestamp where available | | `provenancehash` | Integrity hash for mapping provenance where needed | | `metadata` | JSON for mapping source, consent marker, or external reference | | `timecreated` | Creation timestamp | | `timemodified` | Modification timestamp | Privacy: personal data; full privacy-provider coverage required. ### 6.2 `local_uckk_kx_object_map` Owner: `local_uckk` Purpose: Map Moodle-side objects to Konnaxion objects and Smart Vote targets. | Field | Purpose | |---|---| | `id` | Primary key | | `component` | Moodle component, e.g. `mod_uckkassembly` | | `objecttype` | `assembly`, `motion`, `decision`, `challenge`, `archive_item` | | `objectid` | Moodle-side object id | | `contextid` | Moodle context id | | `externaltype` | Konnaxion object type, e.g. `Vote`, `VoteModality`, `VoteResult`, `IntegrationMapping` | | `externalid` | External Konnaxion object id | | `sourceversion` | External source version/revision/timestamp where available | | `mappingdetails` | JSON matching Konnaxion `IntegrationMapping` expectations | | `mappingstatus` | `draft`, `active`, `suspended`, `superseded`, `archived`, `invalidated` | | `provenancehash` | Integrity hash for mapped record provenance | | `createdby` | Moodle user id | | `timecreated` | Creation timestamp | | `timemodified` | Modification timestamp | Privacy: may contain user ids and institutional object references; privacy-provider coverage required. ### 6.3 `local_uckk_kx_sync_log` Owner: `local_uckk` Purpose: Log Konnaxion sync attempts, retries, failures, endpoint responses, and idempotency keys without leaking secrets. | Field | Purpose | |---|---| | `id` | Primary key | | `operation` | Sync operation name | | `component` | Moodle component initiating or receiving the sync | | `objecttype` | Moodle object type | | `objectid` | Moodle object id | | `externaltype` | Konnaxion object type | | `externalid` | Konnaxion object id | | `syncstatus` | `queued`, `running`, `succeeded`, `failed`, `retry_waiting`, `skipped`, `disabled` | | `attemptno` | Attempt number | | `idempotencykey` | Stable idempotency key | | `httpstatus` | HTTP status or adapter status | | `errorcode` | Normalized error code | | `errormessage` | Redacted error message | | `metadata` | Redacted sync metadata | | `timecreated` | Creation timestamp | | `timemodified` | Modification timestamp | Privacy: operational logs may contain personal-data references; retention and redaction rules are required. ### 6.4 `uckkassembly_kx_vote_target` Owner: `mod_uckkassembly` Purpose: Map Assembly motions, decisions, or deliberation objects to Konnaxion vote targets. | Field | Purpose | |---|---| | `id` | Primary key | | `assemblyid` | Assembly instance id | | `motionid` | Motion id, nullable for Assembly-level readings | | `contextid` | Moodle context id | | `objectmapid` | Link to `local_uckk_kx_object_map` | | `targettype` | Stable target type | | `targetid` | Stable target id | | `modality` | Smart Vote modality name | | `targetstatus` | `draft`, `mapped`, `active`, `closed`, `archived`, `contested` | | `createdby` | Moodle user id | | `timecreated` | Creation timestamp | | `timemodified` | Modification timestamp | ### 6.5 `uckkassembly_sv_snapshot` Owner: `mod_uckkassembly` Purpose: Store imported Smart Vote result snapshots without duplicating every Konnaxion vote record. | Field | Purpose | |---|---| | `id` | Primary key | | `assemblyid` | Assembly instance id | | `motionid` | Motion id | | `contextid` | Moodle context id | | `votetargetid` | Link to `uckkassembly_kx_vote_target` | | `externaltype` | Konnaxion result object type, e.g. `VoteResult` | | `externalid` | External Konnaxion result id | | `sourceversion` | External result version/revision/timestamp | | `raw_data` | Imported or referenced source facts before interpretation, redacted as configured | | `reading_method` | Vote modality, parameters, thresholds, calculation notes | | `computed_reading` | Non-sovereign Smart Vote output | | `expertise_weight` | Weighted-reading factor where applicable; sensitive when linkable to a user | | `minority_report` | Dissenting or alternative interpretation where applicable | | `integrity_warning` | Flags, anomalies, excluded votes summary, warnings | | `contestation_status` | Contestation state for the snapshot | | `archiveitemid` | Archive item id once archived | | `provenancehash` | Hash of canonical snapshot payload | | `fetchedby` | Moodle user id that imported the snapshot | | `timefetched` | Import timestamp | | `snapshotstatus` | `imported`, `under_review`, `accepted_as_reading`, `contested`, `superseded`, `archived`, `invalidated` | Privacy: personal or derived personal data may exist in snapshot payloads; privacy provider must export/delete/redact according to visibility, retention, and archive rules. ### 6.6 `uckkassembly_sv_result_audit` Owner: `mod_uckkassembly` Purpose: Store review, correction, contestation, and supersession trail for Smart Vote readings. | Field | Purpose | |---|---| | `id` | Primary key | | `snapshotid` | Link to `uckkassembly_sv_snapshot` | | `auditstatus` | `recorded`, `reviewed`, `corrected`, `contested`, `resolved` | | `action` | Review/correction/contestation action | | `reason` | Human-readable reason | | `changedby` | Moodle user id | | `timecreated` | Creation timestamp | | `metadata` | Redacted JSON metadata | ## 7. Target naming contract Use stable target identifiers. ```text targettype = uckk_assembly_motion targetid = moodle:{siteid}:mod_uckkassembly:{cmid}:motion:{motionid} ``` For Assembly-level readings: ```text targettype = uckk_assembly targetid = moodle:{siteid}:mod_uckkassembly:{cmid}:assembly:{assemblyid} ``` For Challenge validation readings, only if later enabled: ```text targettype = uckk_challenge_submission targetid = moodle:{siteid}:mod_uckkchallenge:{cmid}:submission:{submissionid} ``` The mapping must also be registered in Konnaxion `IntegrationMapping` using an adapter-safe payload such as: ```json { "module_name": "uckk_moodle", "context_type": "assembly_motion", "mapping_details": { "moodle_site_id": "...", "component": "mod_uckkassembly", "cmid": "...", "assemblyid": "...", "motionid": "...", "contextid": "...", "callback_policy": "moodle_authority_archive_snapshot" } } ``` ## 8. Smart Vote workflow ### 8.1 Preparation ```text 1. Assembly enters deliberation or voting_or_reading state. 2. Authorized user with mod/uckkassembly:requestsmartvote selects Smart Vote as a reading method. 3. Moodle checks assembly type, context, capability, state transition, and integrity status. 4. local_uckk creates or resolves the Konnaxion object mapping. 5. Moodle sends the mapped target, modality, voting window, eligibility policy, and metadata to Konnaxion. 6. Assembly records event: smart_vote_reading_requested. ``` ### 8.2 Vote collection Two modes are allowed when connected mode is enabled: ```text proxy_vote_from_moodle external_vote_portal ``` `proxy_vote_from_moodle` means Moodle collects the user's intent after Moodle capability/session checks and transmits it to Konnaxion. `external_vote_portal` means Moodle sends participants to Konnaxion; Moodle later imports result snapshots. Both modes require identity mapping, consent/notice where required, and audit events. ### 8.3 Result import ```text 1. Authorized user requests result import or scheduled task imports after voting window closes. 2. local_uckk fetches Konnaxion VoteResult and modality metadata. 3. mod_uckkassembly validates the result against the current motion, mapping, context, expected source version, and target id. 4. Moodle stores a uckkassembly_sv_snapshot. 5. Assembly displays the result as a Smart Vote reading, not a final decision. 6. Assembly records event: smart_vote_snapshot_imported. ``` ### 8.4 Decision publication A final UCKK decision must still include: ```text motion reference decision text decision method participants raw reading where available Smart Vote weighted reading where used reasoning evidence used unresolved objections minority report if applicable appeal/contestation path archive link ``` Smart Vote results cannot automatically call `decision_published`. ### 8.5 Archive output Archive must include, when Smart Vote is used: ```text Assembly metadata motion metadata Smart Vote target mapping vote modality raw vote count or source reference weighted result quorum summary integrity/anomaly flags snapshot hash import timestamp final UCKK decision minority report contestation window archive visibility retention classification ``` The archive item must not expose raw Konnaxion vote records unless the configured visibility and privacy rules explicitly allow it. Standalone archive records may exist without any Smart Vote snapshot. Absence of Smart Vote is valid provenance, not a missing record. ## 9. Optional connected-mode classes These classes are required only for the connected Konnaxion profile. They must not prevent standalone installation when the Konnaxion bridge is disabled. ### 9.1 `local_uckk` ```text local_uckk\service\konnaxion_client local_uckk\service\konnaxion_mapping_service local_uckk\service\konnaxion_sync_service local_uckk\external\create_konnaxion_mapping local_uckk\external\get_konnaxion_mapping local_uckk\external\sync_konnaxion local_uckk\event\konnaxion_mapping_created local_uckk\event\konnaxion_sync_completed ``` ### 9.2 `mod_uckkassembly` ```text mod_uckkassembly\local\smartvote_reading mod_uckkassembly\local\smartvote_snapshot_repository mod_uckkassembly\external\request_smart_vote_reading mod_uckkassembly\external\import_smart_vote_snapshot mod_uckkassembly\external\contest_smart_vote_snapshot mod_uckkassembly\event\smart_vote_reading_requested mod_uckkassembly\event\smart_vote_snapshot_imported mod_uckkassembly\event\smart_vote_snapshot_contested mod_uckkassembly\event\smart_vote_snapshot_archived mod_uckkassembly\output\smartvote_panel mod/uckkassembly/templates/smartvote_panel.mustache mod/uckkassembly/amd/src/smartvote.js ``` ### 9.3 `mod_uckkarchive` ```text mod_uckkarchive\local\smartvote_snapshot_exporter mod_uckkarchive\event\smart_vote_snapshot_archived ``` ### 9.4 `tool_uckkintegrity` ```text tool_uckkintegrity\local\smartvote_anomaly_policy ``` ### 9.5 `report_uckk` ```text report_uckk\table\smartvote_readings_table report_uckk\output\smartvote_report ``` ## 10. External API contract assumptions UCKK-Moodle must not assume Konnaxion internal table names are direct API contracts. The bridge must use stable Konnaxion API endpoints, an approved Konnaxion SDK, or an explicit adapter layer. Minimum expected Konnaxion-side operations: ```text GET /api/smart-vote/modalities POST /api/smart-vote/targets POST /api/smart-vote/votes GET /api/smart-vote/results/{target_type}/{target_id} POST /api/integration-mappings GET /api/ekoh/users/{id}/weights?domain=... GET /api/health ``` If Konnaxion exposes different routes, the Moodle bridge must isolate that difference inside `local_uckk\service\konnaxion_client`. ## 11. Failure and safety rules | Situation | Required behavior | |---|---| | Konnaxion disabled | Hide or disable Smart Vote actions; ordinary Assembly workflow remains available. | | Konnaxion unavailable | Do not fabricate result. Mark Smart Vote reading unavailable. Assembly may continue with a non-Smart-Vote method only if authorized and recorded. | | Identity unmapped | User cannot cast Smart Vote until mapped or may cast only unweighted local Moodle vote if the Assembly permits it. | | Result target mismatch | Reject import and open/offer integrity review. | | Result stale | Warn and require authorized refresh before decision publication. | | Anomaly detected | Pause use of result for final decision until Inquisiteur review, if configured. | | Privacy export requested | Export Moodle-side mapping and snapshots; do not export Konnaxion-side records unless Konnaxion API and consent/rights permit it. | | Deletion request | Delete/anonymize Moodle mapping where allowed; preserve institutional archived decision snapshots according to retention policy. | | Payload contains raw voter identities | Redact before display, report, and archive unless explicitly allowed by visibility and privacy rules. | ## 12. Required tests ### 12.1 Standalone regression tests ```text Konnaxion disabled by default UCKK-Moodle installs without Konnaxion credentials seed tool can create standalone campus without Konnaxion mappings ordinary Assembly workflow works without Smart Vote Smart Vote panels/actions are hidden or disabled when Konnaxion is disabled reports render without Smart Vote data archives can preserve Assembly decisions without Smart Vote snapshots ``` ### 12.2 Connected-mode PHPUnit ```text local_uckk/tests/konnaxion_client_test.php local_uckk/tests/konnaxion_mapping_service_test.php local_uckk/tests/konnaxion_sync_service_test.php local_uckk/tests/privacy/provider_konnaxion_test.php mod_uckkassembly/tests/smartvote_reading_test.php mod_uckkassembly/tests/smartvote_snapshot_test.php mod_uckkassembly/tests/privacy/provider_smartvote_test.php tool_uckkintegrity/tests/smartvote_anomaly_test.php report_uckk/tests/smartvote_report_test.php ``` Required connected-mode coverage, only when connected-mode code is implemented or claimed as supported: ```text authorized user can request Smart Vote reading unauthorized user is denied wrong context is denied identity mapping is privacy-exportable object mapping uses stable target identifiers Konnaxion timeout fails safely result import rejects target mismatch result import rejects invalid modality snapshot hash is reproducible archive export redacts raw voter identity final decision cannot auto-publish from Smart Vote alone integrity anomaly can pause use of reading ``` ### 12.3 Connected-mode Behat ```text mod/uckkassembly/tests/behat/uckkassembly_smartvote.feature local/uckk/tests/behat/konnaxion_bridge.feature report/uckk/tests/behat/smartvote_report.feature ``` User workflow coverage: ```text Gestionnaire enables and configures Konnaxion bridge authorized user verifies identity/object mapping authorized Assembly owner requests Smart Vote reading Joueur casts Smart Vote or follows external vote link authorized user imports Smart Vote result Assembly publishes final decision using Smart Vote as one reading minority report remains visible where policy requires it Archive stores final decision and Smart Vote snapshot unauthorized user cannot view restricted Smart Vote details integrity reviewer contests or invalidates suspicious reading ``` ## 13. Documentation patch list Apply these changes to the UCKK-Moodle documentation set. ### 13.1 `00_master_execution_doctrine.md` Declare: ```text UCKK-Moodle is self-standing. Konnaxion is an optional connected-mode integration. Smart Vote is required only for connected_konnaxion acceptance, not standalone_core acceptance. ``` Split completion and final checks into: ```text core standalone gate optional Konnaxion-connected gate ``` ### 13.2 `01_domain_boundaries_and_glossary.md` Add boundary rows for: ```text Konnaxion EkoH Smart Vote standalone_core connected_konnaxion ``` ### 13.3 `02_distribution_architecture.md` Place Konnaxion under optional Layer 6: ```text Layer 6 — Optional external integrations └── Konnaxion v14 Smart Vote / EkoH bridge ``` Layer 6 must not be a hard dependency for standalone install, seed, Assembly, archive, integrity, report, or tests. ### 13.4 `03_plugin_specifications.md` Add connected-mode Konnaxion bridge responsibilities to `local_uckk`. Add connected-mode Smart Vote reading support to `mod_uckkassembly`. Add connected-mode Smart Vote snapshot display to `report_uckk`. Split all Konnaxion classes into: ```text core required classes optional Konnaxion-connected classes ``` Add explicit rule: ```text Smart Vote is a reading method, not an automatic decision publisher. ``` ### 13.5 `04_data_model_and_storage.md` Add optional connected-mode table rows: ```text local_uckk_kx_user_map local_uckk_kx_object_map local_uckk_kx_sync_log uckkassembly_kx_vote_target uckkassembly_sv_snapshot uckkassembly_sv_result_audit ``` Add privacy-provider and test rows for those tables. ### 13.6 `05_roles_permissions_and_security.md` Use only the canonical capabilities listed in section 5 of this document, unless `DOC_00` is deliberately expanded. Add security rule: ```text External reputation, vote weight, Smart Vote result, Konnaxion role, or external identifier cannot grant Moodle authority by itself. ``` ### 13.7 `06_pedagogy_courses_competencies_badges.md` Clarify that Konnaxion/EkoH/Smart Vote signals are optional connected-mode advisory signals. They cannot auto-complete courses, auto-rate competencies, auto-award badges, or validate UCKK evidence. ### 13.8 `07_challenges_and_assemblies.md` Add Smart Vote as a connected-mode Assembly reading method. Do not remove existing non-Smart-Vote voting/readings. Add explicit standalone rule: ```text Assembly workflows must work without Smart Vote enabled. ``` ### 13.9 `08_integrity_archives_and_privacy.md` Add Smart Vote readings and Konnaxion mappings to connected-mode provenance requirements. Standalone archives may preserve Assembly decisions without Smart Vote snapshots. ### 13.10 `09_integrations_reporting_delivery.md` Split acceptance into: ```text core standalone acceptance checklist optional Konnaxion-connected acceptance checklist ``` Move Konnaxion bridge, Smart Vote import, Smart Vote snapshots, Smart Vote reports, outage behavior, and Konnaxion privacy coverage into the connected-mode checklist. ### 13.11 `11_cross_doc_alignment_registry.md` Ensure `DOC_11` remains the canonical registry for: ```text implemented_now vs target_connected_mode current executable capabilities target connected-mode capabilities deprecated aliases standalone-vs-connected conditionality ``` This contract must follow `DOC_11`; it must not introduce a conflicting capability, table, service, event, or preset name. ### 13.12 `12_current_code_snapshot_gap_report.md` Before code revision, classify each gap as one of: ```text CODE_FIX_STANDALONE_BLOCKER CODE_FIX_CORE_COMPLETION DOC_GATE_CLARIFICATION CONNECTED_MODE_DEFERRED ``` Konnaxion and Smart Vote target items belong in `CONNECTED_MODE_DEFERRED` unless the connected profile is explicitly selected for the current code pass. ### 13.13 Presets Add connected-mode entries only where the corresponding preset file exists. Navigation entry: ```json { "key": "uckk.smartvote", "label_fr": "Lectures Smart Vote", "label_en": "Smart Vote Readings", "component": "mod_uckkassembly", "capability": "mod/uckkassembly:viewsmartvote", "requires": { "enable_konnaxion_bridge": true, "smartvote_enabled": true } } ``` Capability presets must use the canonical capabilities from section 5. ## 14. Connected-mode acceptance gate The Konnaxion Smart Vote bridge is not accepted until all connected-mode checks pass. These checks do not block `standalone_core` acceptance unless the release claims `connected_konnaxion` support: ```text [ ] UCKK-Moodle still installs and operates with Konnaxion disabled. [ ] Konnaxion can be enabled/disabled from Moodle admin settings. [ ] Konnaxion bridge is disabled safely by default. [ ] Moodle can perform a Konnaxion health check without exposing secrets. [ ] Moodle user ↔ Konnaxion user mapping works and is privacy-covered. [ ] Moodle object ↔ Konnaxion object mapping works. [ ] Assembly motion ↔ Konnaxion Smart Vote target mapping works. [ ] Smart Vote reading can be requested only by authorized users. [ ] Result import validates target, modality, context, source version, hash, and state. [ ] Smart Vote result is displayed as a reading, not a final decision. [ ] Final decision publication still requires Moodle capability and state checks. [ ] Archive snapshot stores method, result, hash, provenance, visibility, and contestation path. [ ] Minority report and contestation path remain available. [ ] Integrity reviewer can pause, contest, or invalidate a reading. [ ] Reports enforce context, capability, visibility, and redaction rules. [ ] Privacy export/delete covers mappings, snapshots, logs, and user references. [ ] Konnaxion outage fails safely without fabricating or silently accepting results. [ ] PHPUnit and Behat coverage exists for all critical connected-mode paths. ``` ## 15. Final compatibility statement UCKK-Moodle is self-standing. Konnaxion is an optional connected-mode integration that can add Smart Vote readings, EkoH/advisory signals, and better cross-module organization. Konnaxion never replaces Moodle permissions, UCKK academic authority, Assembly decisions, Archive provenance, Integrity review, privacy rules, or AI non-sovereignty rules. ================================================================================================ FILE: docs/11_cross_doc_alignment_registry.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 4ae1adcbd78f6858eacb969b536fa7baa4d489054693d680c4841656f0163350 CONTENT_BYTES: 35293 ================================================================================================ # 11 — Cross-Document Alignment Registry **Status:** Canonical alignment registry for UCKK-Moodle documentation and implementation correction **Purpose:** Provide one shared source of truth for document paths, operating modes, authority boundaries, plugin ownership, current code-snapshot names, target connected-mode names, deprecated aliases, and drift checks. This file is intentionally a registry, not a narrative specification. Other documentation files must consume these variables instead of redefining them locally. ## 0. Registry authority This registry is binding for cross-document consistency. ```text DOC_00 remains the root doctrine for UCKK-Moodle meaning and authority. DOC_11 resolves cross-document names, paths, aliases, implementation status, and migration targets. If a local documentation file conflicts with DOC_11 on a shared variable, DOC_11 wins unless DOC_00 explicitly overrides it. ``` Every active documentation file must include this rule near the top: ```text This document consumes docs/11_cross_doc_alignment_registry.md. It must not redefine shared variables. If a local rule conflicts with DOC_11, DOC_11 and DOC_00 win. ``` ## 1. Code-snapshot basis This registry is aligned against the UCKK-Moodle code snapshot generated on `2026-05-13T09:21:20`. The snapshot contains the installable plugin suite and docs under these uploaded volume files: ```text uckk-moodle_20260513_092119_01_ROOT.txt uckk-moodle_20260513_092119_02_mod.txt uckk-moodle_20260513_092119_03_admin.txt uckk-moodle_20260513_092119_99_OTHERS.txt ``` The code snapshot currently implements UCKK-Moodle core plugin paths and core Moodle capabilities. It does **not** yet implement Konnaxion/Smart Vote connected-mode tables, services, events, or Smart Vote-specific capabilities in executable code. Therefore: ```text Konnaxion/Smart Vote variables in this registry are connected-mode targets unless marked as implemented_now. A connected-mode target must not be treated as a standalone-core requirement. ``` ## 2. Operating-mode variables | Variable | Canonical value | Status | Rule | |---|---:|---|---| | `OPERATING_MODE_STANDALONE` | `standalone_core` | `implemented_now` | UCKK-Moodle installs, seeds, teaches, deliberates, archives, reports, and passes core tests without Konnaxion. | | `OPERATING_MODE_KONNAXION_CONNECTED` | `connected_konnaxion` | `target_connected_mode` | Optional profile where Konnaxion bridge, Smart Vote readings, EkoH/advisory signals, mappings, sync logs, and connected reports are enabled. | | `KONNAXION_REQUIRED_FOR_CORE` | `false` | `implemented_now` | No plugin may make Konnaxion a hard dependency for standalone install or ordinary UCKK workflows. | | `SMART_VOTE_REQUIRED_FOR_CORE` | `false` | `implemented_now` | Assemblies, archives, reports, integrity review, and seed operations must work without Smart Vote. | | `KONNAXION_DEFAULT_STATE` | `disabled` | `target_connected_mode` | Konnaxion bridge settings, services, tasks, UI panels, and reports are hidden or fail closed until enabled. | | `SMART_VOTE_DEFAULT_STATE` | `disabled_until_connected` | `target_connected_mode` | Smart Vote request/import/report actions are available only in connected mode and only with explicit Moodle capabilities. | | `CORE_RELEASE_GATE` | `standalone_core_install_and_workflows_pass` | `implemented_now` | Core acceptance must not require Konnaxion credentials, endpoints, mappings, Smart Vote snapshots, or Konnaxion reports. | | `CONNECTED_RELEASE_GATE` | `konnaxion_connected_profile_passes` | `target_connected_mode` | Connected acceptance applies only when Konnaxion/Smart Vote features are enabled for that release profile. | ## 3. Document path registry | Variable | Canonical path | Status | Rule | |---|---|---|---| | `DOC_00` | `docs/00_master_execution_doctrine.md` | active | Root doctrine and correction authority. | | `DOC_01` | `docs/01_domain_boundaries_and_glossary.md` | active | Domain vocabulary and boundaries. | | `DOC_02` | `docs/02_distribution_architecture.md` | active | Distribution architecture and dependency direction. | | `DOC_03` | `docs/03_plugin_specifications.md` | active | Plugin implementation contract. | | `DOC_04` | `docs/04_data_model_and_storage.md` | active | Table ownership, enums, state machines, and storage constraints. | | `DOC_05` | `docs/05_roles_permissions_and_security.md` | active | Capability and access-control registry. | | `DOC_06` | `docs/06_pedagogy_courses_competencies_badges.md` | active | Courses, competencies, evidence, and badge rules. | | `DOC_07` | `docs/07_challenges_and_assemblies.md` | active | Challenge, Assembly, readings, decisions, and contestations. | | `DOC_08` | `docs/08_integrity_archives_and_privacy.md` | active | Archive, privacy, retention, redaction, integrity. | | `DOC_09` | `docs/09_integrations_reporting_delivery.md` | active | Integrations, reporting, delivery, release, acceptance. | | `DOC_10` | `docs/10_konnaxion_smart_vote_integration_contract.md` | active_optional_connected_mode | Optional Konnaxion Smart Vote connected-mode contract. | | `DOC_11` | `docs/11_cross_doc_alignment_registry.md` | active | This registry. | | `LEGACY_DOC_10` | `docs/10_implementation_correction_plan.md` | deprecated | Historical correction-plan slot. Must not be active target. | Deprecated and forbidden document variables: ```text OPTIONAL_KONNAXION_CONTRACT ``` Deprecated and forbidden active document path: ```text docs/10_konnaxion_alignment_and_correction_plan.md ``` If that file is later created, it must receive a new variable such as `DOC_12_KONNAXION_ALIGNMENT_PLAN`; it must not replace the active `DOC_10` path above. ## 4. Product boundary registry | Variable | Canonical value | Rule | |---|---|---| | `PRODUCT_SCOPE` | `UCKK-Moodle is the Moodle campus implementation of UCKK.` | UCKK-Moodle is not the whole kOA movement or the whole Konnaxion ecosystem. | | `SOURCE_FAMILY_UCKK_CANON` | `UCKK canon` | Governs UCKK meaning, pedagogy, governance, and symbolic boundaries. | | `SOURCE_FAMILY_MOODLE_DOCS` | `Moodle developer documentation` | Governs Moodle implementation mechanics. | | `SOURCE_FAMILY_KONNAXION` | `Konnaxion external source family` | External source of truth for Konnaxion-side Smart Vote objects and semantics. | | `EXTERNAL_SYSTEM_KONNAXION` | `Konnaxion` | External system integrated through Moodle services only. | | `EXTERNAL_SIGNAL_EKOH` | `EkoH` | External expertise/ethics/reputation context or signal source only where explicitly mapped. | ## 5. Non-negotiable authority variables | Variable | Canonical value | Rule | |---|---|---| | `SMART_VOTE_CANONICAL_RULE` | `Konnaxion computes Smart Vote readings. UCKK-Moodle owns Assembly decisions. Archives preserve both, with provenance and contestability.` | Must be preserved anywhere Smart Vote is referenced. | | `SMART_VOTE_AUTHORITY` | `computed_reading_only` | Smart Vote may inform; it must not decide, award, validate, sanction, publish final decisions, or close contestations. | | `ASSEMBLY_AUTHORITY` | `human_institutional_decision` | Final Assembly decisions belong to Moodle-side Assembly workflow and permissions. | | `ARCHIVE_AUTHORITY` | `provenance_and_contestation_memory` | Archives preserve source, snapshot, decision, minority report, provenance, and contestation trail. | | `PERMISSION_RULE` | `moodle_capabilities_remain_authoritative` | External roles, labels, identifiers, weights, or scores never grant Moodle authority by themselves. | | `DIRECT_WRITE_RULE` | `external_systems_never_write_moodle_source_tables` | Konnaxion and other external systems must not write directly into Moodle source tables. | | `AI_AUTHORITY` | `assistive_only` | AI outputs are drafts/explanations and never final authority. | ## 6. Plugin component registry These are the canonical Moodle component names and install paths present in the code snapshot. | Component | Path | Status | Role | |---|---|---|---| | `theme_uckk` | `theme/uckk` | implemented_now | Visual identity and layouts. | | `format_uckk` | `course/format/uckk` | implemented_now | UCKK course format. | | `local_uckk` | `local/uckk` | implemented_now | Core registry, shared services, profiles, programs, pathways, integration coordination. | | `block_uckk_dashboard` | `blocks/uckk_dashboard` | implemented_now | Dashboard display aggregator. | | `mod_uckkchallenge` | `mod/uckkchallenge` | implemented_now | Challenge activity. | | `mod_uckkassembly` | `mod/uckkassembly` | implemented_now | Assembly activity and ordinary votes/readings/decisions. | | `mod_uckkarchive` | `mod/uckkarchive` | implemented_now | Archive activity and evidence/provenance preservation. | | `tool_uckkseed` | `admin/tool/uckkseed` | implemented_now | Campus seed and preset operations. | | `tool_uckkintegrity` | `admin/tool/uckkintegrity` | implemented_now | Integrity/Inquisiteur workflow. | | `report_uckk` | `report/uckk` | implemented_now | Institutional reporting. | | `aiprovider_uckk` | `ai/provider/uckk` | implemented_now | Governed AI provider. | Forbidden component roots unless used only as packaging/staging directories: ```text plugins/mod/uckkarchive plugins/local/uckk plugins/theme/uckk local_uckkkonnaxion mod_uckksmartvote report_uckksmartvote ``` A separate Konnaxion plugin may be introduced only through a new architecture decision. Until then, Konnaxion-connected mode is owned through the existing suite. ## 7. Plugin ownership variables | Variable | Canonical owner | Status | Responsibilities | |---|---|---|---| | `KONNAXION_BRIDGE_OWNER` | `local_uckk` | target_connected_mode | Configuration, endpoint client, authentication settings, object mapping, identity mapping, sync logs, shared integration services. | | `SMART_VOTE_WORKFLOW_OWNER` | `mod_uckkassembly` | target_connected_mode | Smart Vote reading requests, vote-target mapping, snapshots, review, contestation, Assembly linkage. | | `ASSEMBLY_DECISION_OWNER` | `mod_uckkassembly` | implemented_now | Motions, deliberation, decisions, minutes, minority reports, decision contestability. | | `SMART_VOTE_ARCHIVE_OWNER` | `mod_uckkarchive` | target_connected_mode | Archive records and file areas for Smart Vote snapshots, decisions, minutes, provenance packages. | | `ARCHIVE_RECORD_OWNER` | `mod_uckkarchive` | implemented_now | Archive items, proofs, Kristals, provenance, revisions, exports. | | `SMART_VOTE_REPORT_OWNER` | `report_uckk` | target_connected_mode | Smart Vote reports, exports, filters, privacy-aware visibility. | | `REPORT_OWNER` | `report_uckk` | implemented_now | UCKK institutional reports. | | `SMART_VOTE_INTEGRITY_OWNER` | `tool_uckkintegrity` | target_connected_mode | Integrity warnings, contested readings, correction cases, restricted review workflows. | | `INTEGRITY_OWNER` | `tool_uckkintegrity` | implemented_now | Integrity cases, notes, appeals, reviews, corrections. | | `SMART_VOTE_SEED_OWNER` | `tool_uckkseed` | target_connected_mode | Optional connected-mode presets for capabilities, mappings, reports, retention. | | `SEED_OWNER` | `tool_uckkseed` | implemented_now | Core campus seed, validation, export, reset, logs. | | `SMART_VOTE_PRIVACY_OWNER` | `every_storing_plugin` | target_connected_mode | Each plugin that stores Smart Vote/Konnaxion personal data owns its own provider coverage. | ## 8. Current implemented capability registry These capabilities are present in the current code snapshot and may be used in standalone-core documentation. ### 8.1 `local_uckk` ```text local/uckk:viewcampus local/uckk:manageprograms local/uckk:managepathways local/uckk:manageprofiles local/uckk:managecanon local/uckk:viewreports local/uckk:exportdata local/uckk:viewrestricted local/uckk:manageintegrations ``` `local/uckk:manageintegrations` is the current implemented integration-administration capability. Until a narrower connected-mode Konnaxion capability migration is implemented, docs must not claim that `local/uckk:managekonnaxion`, `local/uckk:mapkonnaxionobjects`, or `local/uckk:viewkonnaxionlogs` exist in executable code. ### 8.2 `mod_uckkassembly` ```text mod/uckkassembly:addinstance mod/uckkassembly:view mod/uckkassembly:createassembly mod/uckkassembly:proposemotion mod/uckkassembly:amendmotion mod/uckkassembly:vote mod/uckkassembly:publishdecision mod/uckkassembly:contestdecision mod/uckkassembly:archive ``` No Smart Vote-specific Assembly capability is implemented in the current code snapshot. ### 8.3 `mod_uckkarchive` ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` No Smart Vote-specific Archive capability is implemented in the current code snapshot. ### 8.4 `report_uckk` ```text report/uckk:view report/uckk:viewall report/uckk:export ``` No Smart Vote-specific Report capability is implemented in the current code snapshot. ### 8.5 `tool_uckkintegrity` ```text tool/uckkintegrity:view tool/uckkintegrity:opencase tool/uckkintegrity:reviewcase tool/uckkintegrity:assigncase tool/uckkintegrity:issuecorrection tool/uckkintegrity:invalidate tool/uckkintegrity:closecase tool/uckkintegrity:viewrestricted ``` ### 8.6 `tool_uckkseed` ```text tool/uckkseed:seed tool/uckkseed:reset tool/uckkseed:validate tool/uckkseed:exportpresets ``` ### 8.7 Other implemented capabilities ```text format/uckk:viewcoursemap format/uckk:viewevidenceindicators format/uckk:viewarchiveindicators format/uckk:viewintegritymarkers format/uckk:configuresections format/uckk:manageblueprint format/uckk:resetsectionnames format/uckk:viewdiagnostics block/uckk_dashboard:addinstance block/uckk_dashboard:myaddinstance block/uckk_dashboard:view block/uckk_dashboard:viewothers block/uckk_dashboard:configure aiprovider/uckk:configure aiprovider/uckk:use aiprovider/uckk:viewlogs ``` ## 9. Target connected-mode capability registry These variables are allowed as connected-mode targets only. They are not current standalone-core facts until implemented in `db/access.php`, presets, language strings, PHPUnit tests, Behat tests, and service/page checks. | Variable | Target capability | Owner | Status | Implementation rule | |---|---|---|---|---| | `CAP_MANAGE_KONNAXION` | `local/uckk:manageintegrations` | `local_uckk` | implemented_now_as_generic | Use current generic integration capability unless a narrower migration is implemented. | | `CAP_MAP_KONNAXION_OBJECTS` | `local/uckk:manageintegrations` | `local_uckk` | implemented_now_as_generic | Mapping administration is covered by `manageintegrations` until a narrower capability exists. | | `CAP_VIEW_KONNAXION_LOGS` | `local/uckk:manageintegrations` | `local_uckk` | implemented_now_as_generic | Sync/status logs are integration-admin data until a narrower capability exists. | | `CAP_REQUEST_SMART_VOTE` | `mod/uckkassembly:requestsmartvote` | `mod_uckkassembly` | target_connected_mode | Must be added before Smart Vote request UI/service is enabled. | | `CAP_VIEW_SMART_VOTE` | `mod/uckkassembly:viewsmartvote` | `mod_uckkassembly` | target_connected_mode | Must be added before Smart Vote readings are displayed. | | `CAP_REVIEW_SMART_VOTE` | `mod/uckkassembly:reviewsmartvote` | `mod_uckkassembly` | target_connected_mode | Must be added before review/import workflow is enabled. | | `CAP_CONTEST_SMART_VOTE` | `mod/uckkassembly:contestsmartvote` | `mod_uckkassembly` | target_connected_mode | Must be added before Smart Vote contestation is enabled. | | `CAP_ARCHIVE_SMART_VOTE` | `mod/uckkarchive:archivesmartvote` | `mod_uckkarchive` | target_connected_mode | Must be added before Smart Vote archive action is enabled. | | `CAP_VIEW_SMART_VOTE_REPORTS` | `report/uckk:viewsmartvotereports` | `report_uckk` | target_connected_mode | Must be added before Smart Vote reports are enabled. | ### 9.1 Capability migration rule If the project chooses to introduce narrower Konnaxion capabilities later, the migration must update all of these together: ```text db/access.php presets/capabilities.json admin/tool/uckkseed/presets/capabilities.json language strings service/page capability checks role presets PHPUnit allow/deny tests Behat visibility tests docs/05_roles_permissions_and_security.md docs/11_cross_doc_alignment_registry.md ``` Until that migration exists, documentation must not state that the narrower `local/uckk:*konnaxion*` capabilities are implemented. ## 10. Deprecated and forbidden capability aliases The following names must not be used as active canonical values. ```text local/uckk:managekonnaxion local/uckk:configurekonnaxion local/uckk:managekonnaxionmappings local/uckk:managekonnaxionidentitymap local/uckk:managekonnaxionobjectmap local/uckk:mapkonnaxionobjects local/uckk:viewkonnaxionstatus local/uckk:viewkonnaxionlogs local/uckk:syncsmartvote local/uckk:viewsmartvotelogs mod/uckkassembly:opensmartvote mod/uckkassembly:viewsmarkvotereading mod/uckkassembly:viewsmartvotereading mod/uckkassembly:usesmartvote mod/uckkassembly:exportsmartvotetarget mod/uckkassembly:importsmartvoteresult mod/uckkassembly:invalidatesmartvote mod/uckkassembly:contestsmartvotereading mod/uckkarchive:viewsmartvotesnapshot mod/uckkarchive:archivesmartvotesnapshot report/uckk:viewsmartvote report/uckk:exportsmartvote report/uckk:viewkonnaxionlogs ``` Special typo ban: ```text mod/uckkassembly:viewsmarkvotereading ``` This typo must never appear in final code, presets, or active documentation except inside this deprecated-alias registry. ## 11. Current implemented table registry These tables exist in the current code snapshot and are valid standalone-core tables. ### 11.1 `local_uckk` ```text local_uckk_program local_uckk_pathway local_uckk_player local_uckk_role local_uckk_canon local_uckk_prov local_uckk_reflect local_uckk_map local_uckk_pathway_stat ``` ### 11.2 `mod_uckkassembly` ```text uckkassembly uckkassembly_motion uckkassembly_amend uckkassembly_object uckkassembly_vote uckkassembly_decision uckkassembly_minutes uckkassembly_contest ``` ### 11.3 `mod_uckkarchive` ```text uckkarchive uckkarchive_item uckkarchive_kristal uckkarchive_proof uckkarchive_prov uckkarchive_rev uckkarchive_export ``` ### 11.4 Admin and AI tables ```text tool_uckkseed_run tool_uckkseed_log tool_uckkintegrity_case tool_uckkintegrity_note tool_uckkintegrity_appeal aiprovider_uckk_log ``` ## 12. Target connected-mode table registry These tables are target connected-mode tables. They are not current code-snapshot tables and must not be required for standalone-core install or tests until implemented. | Variable | Target table | Owner | Status | Rule | |---|---|---|---|---| | `TABLE_KONNAXION_USER_MAP` | `local_uckk_kx_user_map` | `local_uckk` | target_connected_mode | Maps Moodle users to Konnaxion identities without unnecessary external personal data. | | `TABLE_KONNAXION_OBJECT_MAP` | `local_uckk_kx_object_map` | `local_uckk` | target_connected_mode | Maps Moodle objects to Konnaxion objects. | | `TABLE_KONNAXION_SYNC_LOG` | `local_uckk_kx_sync_log` | `local_uckk` | target_connected_mode | Logs sync attempts, failures, retries, endpoint responses, and idempotency keys. | | `TABLE_SMART_VOTE_TARGET_MAP` | `uckkassembly_kx_vote_target` | `mod_uckkassembly` | target_connected_mode | Maps Assembly motions, decisions, or deliberation objects to Konnaxion vote targets. | | `TABLE_SMART_VOTE_SNAPSHOT` | `uckkassembly_sv_snapshot` | `mod_uckkassembly` | target_connected_mode | Stores Moodle-side immutable Smart Vote reading snapshots. | | `TABLE_SMART_VOTE_RESULT_AUDIT` | `uckkassembly_sv_result_audit` | `mod_uckkassembly` | target_connected_mode | Stores review, correction, contestation, and supersession trail for Smart Vote results. | The abbreviation `kx` is allowed only in table and internal variable names. User-facing documentation and UI must use `Konnaxion`. Deprecated table names: ```text local_uckk_konnaxion_identity_map local_uckk_konnaxion_object_map uckkassembly_smartvote_snapshot uckkassembly_smartvote_result uckkassembly_smartvote_audit ``` ## 13. Current implemented service registry These service functions exist in the current code snapshot and are valid standalone-core service names. ### 13.1 `local_uckk` ```text local_uckk_get_player_dashboard local_uckk_get_programs local_uckk_get_pathways local_uckk_get_pathway_map local_uckk_get_player_profile local_uckk_update_player_profile local_uckk_get_canon_items local_uckk_get_status_options ``` ### 13.2 `mod_uckkassembly` ```text mod_uckkassembly_get_assembly_state mod_uckkassembly_get_motion_list mod_uckkassembly_get_motion mod_uckkassembly_submit_motion mod_uckkassembly_submit_amendment mod_uckkassembly_submit_objection mod_uckkassembly_submit_vote mod_uckkassembly_get_vote_results mod_uckkassembly_get_decision mod_uckkassembly_publish_decision mod_uckkassembly_contest_decision mod_uckkassembly_get_minutes_panel mod_uckkassembly_save_minutes mod_uckkassembly_publish_minutes mod_uckkassembly_get_integrity_panel mod_uckkassembly_open_integrity_case mod_uckkassembly_get_archive_preview mod_uckkassembly_archive_assembly ``` ### 13.3 `mod_uckkarchive` ```text mod_uckkarchive_get_archive mod_uckkarchive_get_archive_items mod_uckkarchive_get_archive_item mod_uckkarchive_get_archive_item_card mod_uckkarchive_get_proofs mod_uckkarchive_get_provenance_panel mod_uckkarchive_get_kristal mod_uckkarchive_get_revisions mod_uckkarchive_get_restricted_item mod_uckkarchive_save_item_draft mod_uckkarchive_add_item mod_uckkarchive_add_proof mod_uckkarchive_update_provenance mod_uckkarchive_validate_item mod_uckkarchive_revise_item mod_uckkarchive_create_kristal mod_uckkarchive_update_kristal mod_uckkarchive_get_export_preview mod_uckkarchive_export_items mod_uckkarchive_get_export_status ``` ### 13.4 `tool_uckkintegrity` ```text tool_uckkintegrity_open_case ``` ## 14. Target connected-mode service and event registry These names are target connected-mode names. They must not be declared as active until matching classes, access checks, privacy handling, tests, and UI gates exist. | Variable | Target name | Owner | Status | |---|---|---|---| | `SERVICE_CREATE_KONNAXION_MAPPING` | `local_uckk_create_konnaxion_mapping` | `local_uckk` | target_connected_mode | | `SERVICE_GET_KONNAXION_MAPPING` | `local_uckk_get_konnaxion_mapping` | `local_uckk` | target_connected_mode | | `SERVICE_SYNC_KONNAXION` | `local_uckk_sync_konnaxion` | `local_uckk` | target_connected_mode | | `SERVICE_REQUEST_SMART_VOTE_READING` | `mod_uckkassembly_request_smart_vote_reading` | `mod_uckkassembly` | target_connected_mode | | `SERVICE_IMPORT_SMART_VOTE_SNAPSHOT` | `mod_uckkassembly_import_smart_vote_snapshot` | `mod_uckkassembly` | target_connected_mode | | `SERVICE_CONTEST_SMART_VOTE_SNAPSHOT` | `mod_uckkassembly_contest_smart_vote_snapshot` | `mod_uckkassembly` | target_connected_mode | | `SERVICE_GET_SMART_VOTE_REPORT` | `report_uckk_get_smart_vote_report` | `report_uckk` | target_connected_mode | | `EVENT_KONNAXION_MAPPING_CREATED` | `local_uckk\\event\\konnaxion_mapping_created` | `local_uckk` | target_connected_mode | | `EVENT_KONNAXION_SYNC_COMPLETED` | `local_uckk\\event\\konnaxion_sync_completed` | `local_uckk` | target_connected_mode | | `EVENT_SMART_VOTE_READING_REQUESTED` | `mod_uckkassembly\\event\\smart_vote_reading_requested` | `mod_uckkassembly` | target_connected_mode | | `EVENT_SMART_VOTE_SNAPSHOT_IMPORTED` | `mod_uckkassembly\\event\\smart_vote_snapshot_imported` | `mod_uckkassembly` | target_connected_mode | | `EVENT_SMART_VOTE_SNAPSHOT_CONTESTED` | `mod_uckkassembly\\event\\smart_vote_snapshot_contested` | `mod_uckkassembly` | target_connected_mode | | `EVENT_SMART_VOTE_SNAPSHOT_ARCHIVED` | `mod_uckkassembly\\event\\smart_vote_snapshot_archived` | `mod_uckkassembly` | target_connected_mode | ## 15. Konnaxion object and field registry These are semantic references to Konnaxion-side objects. Moodle code must access them only through an approved API, SDK, or adapter. | Variable | Canonical external object | Moodle-side rule | |---|---|---| | `KONNAXION_OBJECT_VOTE` | `Vote` | External vote object mapped to a Moodle-side vote target or reading source. | | `KONNAXION_OBJECT_VOTE_MODALITY` | `VoteModality` | External voting modality/method mapped to a Moodle-side reading method. | | `KONNAXION_OBJECT_VOTE_RESULT` | `VoteResult` | External result mapped into a Moodle-side Smart Vote reading snapshot. | | `KONNAXION_OBJECT_INTEGRATION_MAPPING` | `IntegrationMapping` | External mapping object mirrored by Moodle-side mapping tables. | | `KONNAXION_OBJECT_USER_EXPERTISE_SCORE` | `UserExpertiseScore` | External metadata only; never Moodle authority. | | `KONNAXION_OBJECT_USER_ETHICS_SCORE` | `UserEthicsScore` | External metadata only; never Moodle authority. | | `KONNAXION_OBJECT_CONFIDENTIALITY_SETTING` | `ConfidentialitySetting` | External metadata only; must not bypass Moodle visibility. | | `KONNAXION_OBJECT_SCORE_HISTORY` | `ScoreHistory` | External metadata only; must not become Moodle source record. | Moodle-side field keys: | Variable | Canonical field/key | Rule | |---|---|---| | `KONNAXION_EXTERNAL_ID_FIELD` | `externalid` | Stores the Konnaxion identifier; never stores secrets. | | `KONNAXION_EXTERNAL_TYPE_FIELD` | `externaltype` | Stores the Konnaxion object type. | | `KONNAXION_SOURCE_VERSION_FIELD` | `sourceversion` | Stores the external source version, revision, or timestamp where available. | | `KONNAXION_SYNC_STATUS_FIELD` | `syncstatus` | Stores Moodle-side sync state using `KONNAXION_SYNC_STATUS_ENUM`. | | `KONNAXION_PROVENANCE_HASH_FIELD` | `provenancehash` | Stores integrity hash for imported snapshots or mapped records where needed. | ## 16. Smart Vote reading field registry | Variable | Canonical field/key | Rule | |---|---|---| | `SV_RAW_DATA` | `raw_data` | Imported or referenced source facts before interpretation. | | `SV_READING_METHOD` | `reading_method` | Declared method, modality, weighting, or algorithmic reading rule. | | `SV_COMPUTED_READING` | `computed_reading` | Non-sovereign Smart Vote output. | | `SV_EXPERTISE_WEIGHT` | `expertise_weight` | Weighted-reading factor; personal or sensitive where linkable to a user. | | `SV_HUMAN_DECISION` | `human_institutional_decision` | Moodle-side Assembly decision; must not be overwritten by Smart Vote. | | `SV_MINORITY_REPORT` | `minority_report` | Documented minority position or dissenting signal. | | `SV_INTEGRITY_WARNING` | `integrity_warning` | Warning or flag that may open integrity review but is not itself a sanction. | | `SV_CONTESTATION_STATUS` | `contestation_status` | Contestation state for the snapshot or decision linkage. | | `SV_ARCHIVE_ITEM_ID` | `archiveitemid` | Link to preserved archive item when archived. | ## 17. Status and state registry These are connected-mode target enums. They must not be required by standalone-core code until matching tables/classes exist. | Variable | Allowed values | Owner | Status | |---|---|---|---| | `KONNAXION_SYNC_STATUS_ENUM` | `queued`, `running`, `succeeded`, `failed`, `retry_waiting`, `skipped`, `disabled` | `local_uckk` | target_connected_mode | | `KONNAXION_MAPPING_STATUS_ENUM` | `draft`, `active`, `suspended`, `superseded`, `archived`, `invalidated` | `local_uckk` | target_connected_mode | | `SMART_VOTE_TARGET_STATUS_ENUM` | `draft`, `mapped`, `active`, `closed`, `archived`, `contested` | `mod_uckkassembly` | target_connected_mode | | `SMART_VOTE_SNAPSHOT_STATUS_ENUM` | `imported`, `under_review`, `accepted_as_reading`, `contested`, `superseded`, `archived`, `invalidated` | `mod_uckkassembly` | target_connected_mode | | `SMART_VOTE_AUDIT_STATUS_ENUM` | `recorded`, `reviewed`, `corrected`, `contested`, `resolved` | `mod_uckkassembly` | target_connected_mode | ## 18. Preset registry The code snapshot contains both runtime preset locations and repository-level preset mirrors. Runtime docs should prefer `admin/tool/uckkseed/presets/*` when referring to installed Moodle behavior. | Variable | Canonical runtime preset | Repository mirror | Status | Rule | |---|---|---|---|---| | `PRESET_CAPABILITIES` | `admin/tool/uckkseed/presets/capabilities.json` | `uckk-presets/capabilities.json` | implemented_now | Roles and capabilities. | | `PRESET_CATEGORIES` | `admin/tool/uckkseed/presets/categories.json` | `uckk-presets/categories.json` | implemented_now | Course categories. | | `PRESET_COURSES` | `admin/tool/uckkseed/presets/courses.json` | `uckk-presets/courses.json` | implemented_now | Courses. | | `PRESET_COURSE_TEMPLATES` | `admin/tool/uckkseed/presets/course_templates.json` | `uckk-presets/course_templates.json` | implemented_now | Course templates. | | `PRESET_COHORTS` | `admin/tool/uckkseed/presets/cohorts.json` | `uckk-presets/cohorts.json` | implemented_now | Cohorts. | | `PRESET_ROLES` | `admin/tool/uckkseed/presets/roles.json` | `uckk-presets/roles.json` | implemented_now | Role definitions. | | `PRESET_COMPETENCIES` | `admin/tool/uckkseed/presets/competencies.json` | `uckk-presets/competencies.json` | implemented_now | Competencies. | | `PRESET_BADGES` | `admin/tool/uckkseed/presets/badges.json` | `uckk-presets/badges.json` | implemented_now | Badges. | | `PRESET_REPORTS` | `admin/tool/uckkseed/presets/reports.json` | `uckk-presets/reports.json` | implemented_now | Report seed definitions. | | `PRESET_ARCHIVE_TEMPLATES` | `admin/tool/uckkseed/presets/archive_templates.json` | `uckk-presets/archive_templates.json` | implemented_now | Archive templates. | | `PRESET_ASSEMBLY_TEMPLATES` | `admin/tool/uckkseed/presets/assembly_templates.json` | `uckk-presets/assembly_templates.json` | implemented_now | Assembly templates. | | `PRESET_CHALLENGE_TEMPLATES` | `admin/tool/uckkseed/presets/challenge_templates.json` | `uckk-presets/challenge_templates.json` | implemented_now | Challenge templates. | | `PRESET_STATE_MACHINES` | `admin/tool/uckkseed/presets/state_machines.json` | `uckk-presets/state_machines.json` | target_or_missing_in_snapshot | Must exist before docs make it a hard seed input. | | `PRESET_EVENTS` | `admin/tool/uckkseed/presets/events.json` | `uckk-presets/events.json` | target_or_missing_in_snapshot | Must exist before docs make it a hard seed input. | | `PRESET_KONNAXION_MAPPINGS` | `admin/tool/uckkseed/presets/konnaxion_mappings.json` | `uckk-presets/konnaxion_mappings.json` | target_connected_mode | Must not be required for standalone-core seed. | | `PRESET_PRIVACY_RETENTION` | `admin/tool/uckkseed/presets/privacy_retention.json` | `uckk-presets/privacy_retention.json` | target_or_missing_in_snapshot | Must exist before docs make it a hard seed input. | | `PRESET_EXPORTS` | `admin/tool/uckkseed/presets/exports.json` | `uckk-presets/exports.json` | target_or_missing_in_snapshot | Must exist before docs make it a hard seed input. | Docs may use short paths such as `presets/capabilities.json` only when the surrounding text explicitly means “packaged preset path.” Runtime implementation docs should use the full `admin/tool/uckkseed/presets/...` path. ## 19. Conditionality matrix | Requirement | `standalone_core` | `connected_konnaxion` | |---|---|---| | Moodle plugin installation | required | required | | Core seed dry-run/apply | required | required | | Konnaxion credentials/endpoints | forbidden as requirement | required when enabled | | Ordinary Assembly motions/votes/readings/decisions | required | required | | Smart Vote request/import/review/contest/archive/report | not required; hidden/fail-closed | required | | Archive evidence/provenance/versioning | required | required | | Smart Vote snapshot archive | not required | required if Smart Vote used in decision context | | Integrity cases | required | required | | Smart Vote anomaly/integrity review | not required | required | | Core UCKK reports | required | required | | Konnaxion/Smart Vote reports | not required | required | | AI provider configurable/disableable | required | required | | Konnaxion outage/retry/idempotency tests | not required | required | | Privacy provider coverage for core records | required | required | | Privacy provider coverage for Konnaxion/Smart Vote records | not required unless stored | required when stored/exposed | ## 20. Required reference line for each doc Each documentation file from `DOC_00` through `DOC_10` must include this line near the top: ```text This document consumes docs/11_cross_doc_alignment_registry.md for shared variables, document paths, capability names, table names, operating modes, deprecated aliases, and standalone-vs-connected requirements. ``` ## 21. Drift detection rules ### 21.1 Deprecated document path detector The following should return no active references except inside this registry or explicit migration notes: ```bash grep -RIn '10_konnaxion_alignment_and_correction_plan.md\|OPTIONAL_KONNAXION_CONTRACT\|10_implementation_correction_plan.md' docs/ release/ admin/tool/uckkseed/presets/ uckk-presets/ || true ``` ### 21.2 Deprecated capability detector The following should return no active references except inside this registry or explicit migration notes: ```bash grep -RIn 'configurekonnaxion\|managekonnaxion\|mapkonnaxionobjects\|viewkonnaxionlogs\|usesmartvote\|viewsmarkvotereading\|viewsmartvotereading\|opensmartvote\|importsmartvoteresult\|exportsmartvotesnapshot\|contestsmartvotereading' docs/ admin/tool/uckkseed/presets/ uckk-presets/ local/ mod/ report/ || true ``` ### 21.3 Connected-mode target detector The following may return references in docs, but executable code must contain matching classes before connected mode is considered implemented: ```bash grep -RIn 'local_uckk_kx_user_map\|local_uckk_kx_object_map\|local_uckk_kx_sync_log\|uckkassembly_kx_vote_target\|uckkassembly_sv_snapshot\|uckkassembly_sv_result_audit' docs/ local/ mod/ report/ admin/tool/uckkseed/presets/ uckk-presets/ || true ``` ### 21.4 Filetype blocker detector The code snapshot contains generated-file risks. These are implementation blockers, not documentation variables: ```bash grep -RIn --include='*.js' '.php ``` Ces overrides doivent être rares, testés, et ne doivent jamais remplacer `*.faculty.json`. --- # 5. Composants Moodle impliqués | Composant | Rôle dans cette extension | | -------------------- | ------------------------------------------------------------------------------------------------------ | | `local_uckk` | propriétaire de la lecture Atlas, profils de faculté, pages publiques, mapping Moodle, registry, cache | | `tool_uckkseed` | peut générer ou appliquer catégories, cours, champs custom, badges, compétences depuis les JSON | | `format_uckk` | peut rendre les cours Moodle selon le format UCKK | | `theme_uckk` | identité visuelle publique, sans logique métier | | `report_uckk` | rapports d’alignement, sync, validation, cohérence | | `mod_uckkarchive` | peut servir plus tard aux Kristals, preuves et archives publiques filtrées | | `mod_uckkassembly` | non requis pour les pages de facultés; utile seulement pour décisions et gouvernance | | `mod_uckkchallenge` | non requis pour les pages de facultés; utile pour défis liés aux cours | | `tool_uckkintegrity` | peut valider les garde-fous publics et signaler les dérives | --- # 6. Contrat d’autorité ## 6.1 Ordre d’autorité Lorsqu’une IA doit décider quel champ, nom ou comportement appliquer : ```text 1. Ce document DOC_12 2. 00_master_execution_doctrine.md 3. 01_domain_boundaries_and_glossary.md 4. refactor_public_pages_contract.md 5. json_preset_reference.md 6. Les 10 JSON Atlas validés 7. Les 10 JSON Faculty validés 8. Code existant local_uckk ``` ## 6.2 Règle de non-réinterprétation Une IA ne doit pas renommer les identifiants techniques canoniques : ```text Voie → Faculty dans les JSON Atlas Faculty → Voie dans les JSON publics Parchemin → badge public accrédité Smart Vote → décision Konnaxion → Moodle Moodle category → Atlas concept Concept associé → cours Moodle voie_ia_gouvernable → voie_production_ia faculty_ia_gouvernable → faculty_production_ia ia-gouvernable → production-ia ``` Exception documentée : ```text Les identifiants techniques de la Voie IA restent voie_ia_gouvernable, faculty_ia_gouvernable et ia-gouvernable pour compatibilité Atlas/Moodle. L’appellation publique canonique est : Voie de la Production augmentée par l’IA Le nom court public est : Production IA Le nom court éditorial possible est : Production augmentée Le titre symbolique public est : Maître d’œuvre augmenté ``` Règle éditoriale : ```text Ne jamais présenter cette Voie comme une délégation du contrôle à l’IA. Ne jamais laisser croire que kOA donne autorité, décision ou responsabilité à l’IA. Présenter l’IA comme outil de production, de création, de documentation, de code, de graphisme, d’écriture, d’accompagnement et de construction responsable. ``` ## 6.3 Règle de portée Cette extension concerne : ```text pages publiques de facultés lecture des 10 JSON Atlas profils publics de facultés rendu Mustache blocs dynamiques publics mapping Moodle natif préparation de sync Moodle validation anti-drift ``` Elle ne concerne pas : ```text notes privées progression d’un étudiant dossiers personnels badges personnels affichés publiquement votes d’assemblée privés preuves privées Konnaxion Smart Vote IA souveraine accréditation publique ``` --- # 7. Les 10 facultés canoniques ## 7.1 Tableau canonique | Ordre | `voie_id` | Nom public canonique | Nom court public | Titre symbolique public | `faculty_id` | `slug` | `code` | `course_prefix` | `category_idnumber` | `atlas_file` | `faculty_file` | | ----: | -------------------------------------------- | ------------------------------------------------- | ---------------------------------------- | -------------------------------------- | ----------------------------------------------- | --------------------------------------- | ------ | --------------- | ------------------- | ------------------------------------------------- | ---------------------------------------------------- | | 1 | `voie_grand_jeu_social` | Voie du Grand Jeu social | Grand Jeu social | Joueur lucide | `faculty_grand_jeu_social` | `grand-jeu-social` | `GJS` | `GJS` | `UCKK-GJS` | `voie_grand_jeu_social.json` | `grand-jeu-social.faculty.json` | | 2 | `voie_economie` | Voie d’Économie | Économie | Architecte d’opportunités | `faculty_economie` | `economie` | `EC` | `EC` | `UCKK-EC` | `voie_economie.json` | `economie.faculty.json` | | 3 | `voie_ecologie` | Voie d’Écologie | Écologie | Gardien des systèmes vivants | `faculty_ecologie` | `ecologie` | `ECL` | `ECL` | `UCKK-ECL` | `voie_ecologie.json` | `ecologie.faculty.json` | | 4 | `voie_sciences_politiques` | Voie des Sciences politiques | Sciences politiques | Stratège civique | `faculty_sciences_politiques` | `sciences-politiques` | `SP` | `SP` | `UCKK-SP` | `voie_sciences_politiques.json` | `sciences-politiques.faculty.json` | | 5 | `voie_linguistique_architecture_du_sens` | Voie de la Linguistique et de l’architecture du sens | Linguistique et architecture du sens | Architecte du sens | `faculty_linguistique_architecture_du_sens` | `linguistique-architecture-du-sens` | `LI` | `LI` | `UCKK-LI` | `voie_linguistique_architecture_du_sens.json` | `linguistique-architecture-du-sens.faculty.json` | | 6 | `voie_metaphysique` | Voie de la Métaphysique | Métaphysique | Cartographe des structures invisibles | `faculty_metaphysique` | `metaphysique` | `ME` | `ME` | `UCKK-ME` | `voie_metaphysique.json` | `metaphysique.faculty.json` | | 7 | `voie_ia_gouvernable` | Voie de la Production augmentée par l’IA | Production IA | Maître d’œuvre augmenté | `faculty_ia_gouvernable` | `ia-gouvernable` | `IA` | `IA` | `UCKK-IA` | `voie_ia_gouvernable.json` | `ia-gouvernable.faculty.json` | | 8 | `voie_intervention_sociale_systemes_humains` | Voie de l’Intervention sociale et des systèmes humains | Intervention sociale | Gardien de la dignité située | `faculty_intervention_sociale_systemes_humains` | `intervention-sociale-systemes-humains` | `IS` | `IS` | `UCKK-IS` | `voie_intervention_sociale_systemes_humains.json` | `intervention-sociale-systemes-humains.faculty.json` | | 9 | `voie_architecture_sociotechnique` | Voie d’Architecture sociotechnique | Architecture sociotechnique | Architecte des systèmes d’action | `faculty_architecture_sociotechnique` | `architecture-sociotechnique` | `AS` | `AS` | `UCKK-AS` | `voie_architecture_sociotechnique.json` | `architecture-sociotechnique.faculty.json` | | 10 | `voie_ecosysteme_digital_koa` | Voie de l’Architecture de l’écosystème digital kOA | Écosystème digital kOA | Architecte de l’écosystème digital kOA | `faculty_ecosysteme_digital_koa` | `ecosysteme-digital-koa` | `KOA` | `KOA` | `UCKK-KOA` | `voie_ecosysteme_digital_koa.json` | `ecosysteme-digital-koa.faculty.json` | ## 7.2 Interdictions de slugs Ne pas utiliser : ```text grand_jeu_social voie-grand-jeu-social uckk-grand-jeu-social faculte-grand-jeu-social grandjeusocial ``` Utiliser : ```text grand-jeu-social ``` Même règle pour les autres facultés : slugs en minuscules, sans accents, séparés par tirets. ## 7.3 Interdictions de `voie_id` Ne jamais utiliser : ```text voie_intelligence_artificielle_gouvernable ``` Utiliser : ```text voie_ia_gouvernable ``` Ne jamais utiliser : ```text voie_linguistique ``` Utiliser : ```text voie_linguistique_architecture_du_sens ``` Ne jamais utiliser : ```text voie_koa ``` Utiliser : ```text voie_ecosysteme_digital_koa ``` ## 7.4 Appellation publique de la Voie IA La Voie IA conserve ses identifiants techniques historiques pour éviter de casser les liens Atlas, Moodle, catégories, cours, badges et synchronisations. Identifiants techniques à conserver : ```text voie_ia_gouvernable faculty_ia_gouvernable ia-gouvernable voie_ia_gouvernable.json ia-gouvernable.faculty.json IA UCKK-IA IA-HUB ``` Appellation publique canonique : ```text Voie de la Production augmentée par l’IA ``` Nom court public : ```text Production IA ``` Nom court éditorial possible : ```text Production augmentée ``` Titre symbolique public : ```text Maître d’œuvre augmenté ``` Domaine public recommandé : ```text Production outillée ``` Formule publique : ```text Utiliser l’IA pour écrire, concevoir, coder, documenter, créer, accompagner, vérifier et produire des œuvres, outils et systèmes utiles, sans déléguer le jugement humain. ``` Règles : ```text Ne pas utiliser “IA gouvernable” comme nom public principal. Ne pas présenter cette Voie comme une voie de contrôle confié à l’IA. Ne pas écrire que kOA donne le contrôle à l’IA. Ne pas centrer la Voie sur la gouvernance de l’IA comme sujet abstrait. Présenter l’IA comme un outil de production responsable : livres, graphisme, code, documentation institutionnelle, accompagnement, prototypage, recherche, vérification et création. ``` --- # 8. Schéma Atlas de Voie ## 8.1 Nom du schéma | Variable | Valeur | | ---------------------- | -------------------------------------- | | `ATLAS_SCHEMA_VERSION` | `UCKK-ATLAS-0.2-draft` | | `ATLAS_SCHEMA_FILE` | `local/uckk/atlas/atlas_schema.json` | | `ATLAS_MANIFEST_FILE` | `local/uckk/atlas/atlas_manifest.json` | | `ATLAS_VOIE_DIR` | `local/uckk/atlas/voies/` | ## 8.2 Champs top-level obligatoires Chaque `voie_*.json` doit contenir : ```json { "schema_version": "UCKK-ATLAS-0.2-draft", "voie_id": "", "code": "", "nom": "", "domaine_operatoire": "", "niveau_vise": "Puissance opératoire", "titre_symbolique": "", "parchemin": "", "statut": "Voie fondatrice UCKK", "definition_courte": "", "angle_fondamental": "", "competence_centrale": "", "seuils_progression": [], "cours_conceptuels": [], "projet_final": {}, "limites_ethiques": [], "relations_intervoies": [], "tags": [] } ``` ## 8.3 Champs top-level optionnels mais recommandés ```json { "titre_interne_vise": "", "version": "0.2 — normalisation Atlas", "role_dans_atlas": "", "principe_fondateur": "", "distinctions_clefs": [], "risques_specifiques": [], "exigences_gouvernance": [] } ``` ## 8.4 Cours conceptuel Chaque item dans `cours_conceptuels` doit suivre : ```json { "cours_id": "", "ordre": 1, "nom": "", "concept_maitre": { "concept_id": "", "nom": "", "type": "concept_maitre", "definition_courte": "", "fonction_pedagogique": "" }, "concepts_associes": [ { "concept_id": "", "nom": "", "type": "concept_associe", "notions_fines": [] } ], "artefact_maitrise": { "type": "", "nom": "", "description": "" }, "criteres_passage": [], "relations": [] } ``` ## 8.5 Règles de cours Chaque Voie doit avoir exactement 10 cours. ```text cours_conceptuels.length = 10 ordre = 1..10 cours_id = CODE + numéro à trois chiffres ``` Exemples : ```text GJS101 GJS102 ... GJS110 ``` ```text EC101 ... EC110 ``` ## 8.6 Règles de concepts Chaque `concept_maitre` doit avoir : ```json "type": "concept_maitre" ``` Chaque concept associé doit avoir : ```json "type": "concept_associe", "notions_fines": [] ``` Les notions fines restent vides dans cette version. Interdiction : ```json "notions_fines": null ``` Autorisé : ```json "notions_fines": [] ``` ## 8.7 Règle de non-duplication interne Dans un même cours, un `concept_id` ne doit pas apparaître deux fois. Le `concept_id` du concept-maître ne doit pas être répété dans `concepts_associes`. --- # 9. Schéma Faculty Profile ## 9.1 Nom du schéma | Variable | Valeur | | ------------------------ | ---------------------------------------------------- | | `FACULTY_SCHEMA_VERSION` | `UCKK-FACULTY-0.1` | | `FACULTY_SCHEMA_FILE` | `local/uckk/content/faculties/faculty_schema.json` | | `FACULTY_MANIFEST_FILE` | `local/uckk/content/faculties/faculty_manifest.json` | | `FACULTY_PROFILE_DIR` | `local/uckk/content/faculties/` | ## 9.2 Champs obligatoires Chaque `*.faculty.json` doit contenir : ```json { "schema_version": "UCKK-FACULTY-0.1", "faculty_id": "", "voie_id": "", "slug": "", "status": "draft", "visibility": "hidden", "source_atlas": {}, "moodle": {}, "identity": {}, "seo": {}, "hero": {}, "navigation": [], "sections": [], "atlas_projection": {}, "dynamic_blocks": [], "featured_blocks": [], "faq": [], "contact": {}, "governance": {}, "cache": {} } ``` ## 9.3 `status` Allowed values : ```text draft published archived ``` Règles : ```text draft = visible seulement aux éditeurs autorisés published = visible publiquement archived = non listé, affichable seulement si lien direct autorisé ``` ## 9.4 `visibility` Allowed values : ```text public hidden restricted ``` Règles : ```text public = accessible sans login hidden = non accessible publiquement restricted = accès contrôlé par Moodle capability ``` ## 9.5 `source_atlas` Structure obligatoire : ```json { "file": "voie_grand_jeu_social.json", "schema_version_expected": "UCKK-ATLAS-0.2-draft", "sync_mode": "read_only" } ``` Allowed `sync_mode` : ```text read_only preview_only moodle_sync_allowed ``` Règles : ```text read_only = la page lit l’Atlas sans modifier Moodle preview_only = rendu de test, pas public moodle_sync_allowed = les données peuvent servir au dry-run/apply admin ``` ## 9.6 `moodle` Structure obligatoire : ```json { "category_id": null, "category_idnumber": "UCKK-GJS", "course_prefix": "GJS", "public_course_listing": true, "enrolment_visibility": "public_info_only", "hub_course_idnumber": "GJS-HUB" } ``` Allowed `enrolment_visibility` : ```text hidden public_info_only login_required enrolment_required ``` Règles : ```text public_info_only = montrer le programme, pas inscrire automatiquement login_required = afficher certains liens seulement aux utilisateurs connectés enrolment_required = afficher seulement aux inscrits hidden = ne pas afficher les liens Moodle ``` ## 9.7 `identity` Structure obligatoire : ```json { "eyebrow": "Voie UCKK", "name": "", "short_name": "", "title_symbolique": "", "domain": "", "level": "Puissance opératoire", "faculty_role": "", "one_sentence": "" } ``` Règles : ```text identity.name doit correspondre au nom public de la Voie. identity.short_name est le nom court de navigation. identity.title_symbolique doit correspondre au JSON Atlas, sauf override volontaire documenté. identity.domain doit correspondre à domaine_operatoire. identity.level doit correspondre à niveau_vise. ``` ## 9.8 `seo` Structure obligatoire : ```json { "title": "", "description": "", "keywords": [] } ``` Règles : ```text seo.title ne doit pas promettre un diplôme public. seo.description ne doit pas utiliser “université accréditée”. keywords peut contenir UCKK, Voie, domaine, concepts publics. ``` ## 9.9 `hero` Structure obligatoire : ```json { "title": "", "subtitle": "", "summary": "", "primary_cta": { "label": "", "target": "" }, "secondary_cta": { "label": "", "target": "" } } ``` Allowed CTA target : ```text #anchor /local/uckk/... https://... ``` Interdit : ```text javascript: data: file: ``` ## 9.10 `navigation` Structure : ```json [ { "label": "Présentation", "target": "#presentation" } ] ``` Règles : ```text Chaque target doit référencer une section, un bloc dynamique ou un élément rendu. Ne pas créer de target orpheline. Ne pas créer de section sans target si elle est importante. ``` ## 9.11 `sections` Structure : ```json [ { "id": "presentation", "type": "text", "title": "", "body": "" } ] ``` Allowed `section.type` : ```text text markdown quote principle notice cards callout two_column ``` Règles : ```text text = body texte brut filtré markdown = body Markdown filtré côté serveur quote = citation éditoriale principle = principe institutionnel notice = avertissement cards = cartes éditoriales callout = bloc accentué two_column = layout éditorial ``` ## 9.12 `atlas_projection` Structure complète : ```json { "show_definition_courte": true, "show_angle_fondamental": true, "show_competence_centrale": true, "show_seuils_progression": true, "show_courses": true, "show_course_codes": true, "show_concept_maitre": true, "show_concepts_associes": false, "show_artefacts": true, "show_criteres_passage": false, "show_projet_final": true, "show_limites_ethiques": true, "show_relations_intervoies": true, "show_tags": false } ``` Règles : ```text show_concepts_associes = false par défaut pour page publique. show_criteres_passage = false par défaut sauf page détaillée. show_courses = true par défaut. show_projet_final = true par défaut. show_limites_ethiques = true par défaut. ``` ## 9.13 `dynamic_blocks` Structure : ```json [ { "id": "annonces", "type": "announcements", "title": "Annonces de la faculté", "source": { "provider": "moodle_forum", "course_idnumber": "GJS-HUB", "forum_name": "Annonces" }, "limit": 5, "visibility": "public", "empty_state": "Aucune annonce publique pour le moment." } ] ``` Allowed `dynamic_blocks.type` : ```text announcements events moodle_course_list featured_courses faculty_news related_faculties public_resources cta_panel ``` Allowed `source.provider` : ```text moodle_forum moodle_calendar moodle_category moodle_course_customfield local_uckk_news local_uckk_manual none ``` ## 9.14 `featured_blocks` Structure : ```json [ { "type": "principle", "title": "", "body": "" } ] ``` Allowed `featured_blocks.type` : ```text principle notice warning quote stat method ethics cta ``` ## 9.15 `faq` Structure : ```json [ { "question": "", "answer": "" } ] ``` Règles : ```text FAQ publique seulement. Ne pas répondre sur progression individuelle. Ne pas promettre accréditation. Ne pas transformer la FAQ en répétition des limites de reconnaissance. ``` ## 9.16 `contact` Structure : ```json { "label": "Contact", "body": "", "email": "", "cta": { "label": "", "target": "" } } ``` Règles : ```text email peut être vide. target peut pointer vers contact.php ou #annonces. Ne jamais exposer une adresse privée sans consentement. ``` ## 9.17 `governance` Structure obligatoire : ```json { "owner": "local_uckk", "editorial_status": "draft", "last_reviewed": null, "review_notes": "", "public_claims_guardrails": [] } ``` Allowed `editorial_status` : ```text draft review approved needs_update archived ``` Règles : ```text public_claims_guardrails est un champ de gouvernance éditoriale. Il peut rester vide si la page ne contient pas de risque public particulier. S’il est utilisé, il ne doit pas devenir une source de répétition publique. Préférer une seule note institutionnelle discrète lorsque nécessaire. ``` ## 9.18 `cache` Structure obligatoire : ```json { "enabled": true, "ttl_seconds": 3600 } ``` --- # 10. `faculty_manifest.json` ## 10.1 Objet `faculty_manifest.json` liste les 10 facultés autorisées, leurs fichiers, slugs et état public. Aucun slug ne doit être résolu depuis une entrée URL non listée dans ce fichier. ## 10.2 Structure ```json { "schema_version": "UCKK-FACULTY-MANIFEST-0.1", "generated_from": "manual", "items": [ { "faculty_id": "faculty_grand_jeu_social", "voie_id": "voie_grand_jeu_social", "slug": "grand-jeu-social", "faculty_file": "grand-jeu-social.faculty.json", "atlas_file": "voie_grand_jeu_social.json", "status": "published", "visibility": "public", "category_idnumber": "UCKK-GJS", "course_prefix": "GJS", "sortorder": 1 } ] } ``` ## 10.3 Règles de validation Chaque item doit satisfaire : ```text faculty_id unique voie_id unique slug unique faculty_file existe atlas_file existe category_idnumber unique course_prefix unique sauf exception documentée sortorder unique de 1 à 10 ``` --- # 11. `atlas_manifest.json` ## 11.1 Structure ```json { "schema_version": "UCKK-ATLAS-MANIFEST-0.1", "atlas_schema_version": "UCKK-ATLAS-0.2-draft", "items": [ { "voie_id": "voie_grand_jeu_social", "code": "GJS", "nom": "Voie du Grand Jeu social", "file": "voie_grand_jeu_social.json", "course_prefix": "GJS", "category_idnumber": "UCKK-GJS", "sortorder": 1 } ] } ``` ## 11.2 Règles ```text Le manifest Atlas ne contient pas les cours. Le manifest Atlas ne contient pas les sections publiques. Le manifest Atlas ne contient pas les annonces. Il pointe seulement vers les fichiers de Voies et leurs variables stables. ``` --- # 12. Mapping Atlas → Faculty → Moodle ## 12.1 Mapping top-level | Atlas field | Faculty field | Moodle field | Règle | | ---------------------- | --------------------------- | --------------------------- | ----------------------------------------- | | `voie_id` | `voie_id` | custom field `uckk_voie_id` | doit être identique | | `code` | `moodle.course_prefix` | course idnumber prefix | doit être cohérent | | `nom` | `identity.name` | category fullname | peut être adapté publiquement | | `domaine_operatoire` | `identity.domain` | custom field | doit être identique ou override documenté | | `niveau_vise` | `identity.level` | custom field | doit être identique | | `titre_symbolique` | `identity.title_symbolique` | custom field | doit être identique | | `definition_courte` | projection | description publique | dérivé | | `angle_fondamental` | projection | page text | dérivé | | `competence_centrale` | projection | page text | dérivé | | `cours_conceptuels` | projection | Moodle courses | généré | | `projet_final` | projection | capstone activity/course | dérivé | | `limites_ethiques` | projection | notice/page | dérivé | | `relations_intervoies` | projection | related faculty cards | dérivé | | `tags` | SEO / filters | custom field | optionnel | ## 12.2 Mapping cours | Atlas course field | Moodle course field | | --------------------------- | -------------------------------------- | | `cours_id` | `idnumber` and `shortname` | | `nom` | `fullname` | | `ordre` | course sort order | | `concept_maitre.concept_id` | custom field `uckk_concept_maitre_id` | | `concept_maitre.nom` | custom field `uckk_concept_maitre_nom` | | `artefact_maitrise.type` | custom field `uckk_artefact_type` | | `artefact_maitrise.nom` | description / activity title | | `criteres_passage` | completion criteria / rubric text | | `relations` | future graph links | ## 12.3 Course idnumber convention ```text course.idnumber = cours_id course.shortname = cours_id course.fullname = cours_id + " — " + nom ``` Exemple : ```text GJS101 — Cartographie du Grand Jeu social ``` ## 12.4 Hub course convention Chaque faculté peut avoir un hub Moodle public ou semi-public. ```text GJS-HUB EC-HUB ECL-HUB SP-HUB LI-HUB ME-HUB IA-HUB IS-HUB AS-HUB KOA-HUB ``` Le hub sert aux annonces publiques, événements et informations générales. Note : ```text IA-HUB reste l’identifiant technique du hub Moodle. Son nom public doit suivre l’appellation “Production IA” ou “Production augmentée par l’IA”. ``` --- # 13. Champs custom Moodle ## 13.1 Catégories Moodle Custom fields recommandés pour catégories : ```text uckk_faculty_id uckk_voie_id uckk_code uckk_slug uckk_domaine_operatoire uckk_niveau_vise uckk_titre_symbolique uckk_statut uckk_schema_version uckk_faculty_profile_version uckk_atlas_source_hash uckk_faculty_source_hash ``` ## 13.2 Cours Moodle Custom fields recommandés pour cours : ```text uckk_cours_id uckk_voie_id uckk_faculty_id uckk_ordre uckk_concept_maitre_id uckk_concept_maitre_nom uckk_artefact_type uckk_artefact_nom uckk_parchemin uckk_atlas_source_hash uckk_sync_status ``` ## 13.3 Badges / Parchemins Mapping recommandé : ```text Parchemin de Puissance opératoire — Voie du Grand Jeu social → Moodle badge de Voie → idnumber: UCKK-BADGE-GJS-PO ``` Convention : ```text UCKK-BADGE-{CODE}-PO ``` Exemples : ```text UCKK-BADGE-GJS-PO UCKK-BADGE-EC-PO UCKK-BADGE-ECL-PO UCKK-BADGE-SP-PO UCKK-BADGE-LI-PO UCKK-BADGE-ME-PO UCKK-BADGE-IA-PO UCKK-BADGE-IS-PO UCKK-BADGE-AS-PO UCKK-BADGE-KOA-PO ``` --- # 14. Rendu public ## 14.1 Contrôleur Fichier unique : ```text local/uckk/faculty.php ``` Paramètre autorisé : ```text slug ``` Exemple : ```text /local/uckk/faculty.php?slug=grand-jeu-social ``` Règles : ```text slug est obligatoire. slug doit exister dans faculty_manifest.json. Aucun chemin de fichier ne doit être accepté depuis l’URL. La page publique ne doit pas exiger login si visibility=public. La page restricted doit appeler require_login(). ``` ## 14.2 Classe registry ```php local_uckk\local\faculty\faculty_registry ``` Responsabilités : ```text charger faculty_manifest.json résoudre slug → faculty_id résoudre faculty_id → fichiers interdire les slugs inconnus retourner les métadonnées minimales ``` Méthodes canoniques : ```php public static function all(): array; public static function get_by_slug(string $slug): array; public static function get_by_faculty_id(string $facultyid): array; public static function exists_slug(string $slug): bool; ``` ## 14.3 Repositories ### `voie_repository` ```php local_uckk\local\atlas\voie_repository ``` Responsabilités : ```text lire un fichier voie_*.json valider JSON brut retourner array ou DTO normalisé ne pas rendre HTML ne pas interroger Moodle sauf si explicitement mapper ``` Méthodes : ```php public function get_by_voie_id(string $voieid): array; public function get_by_file(string $filename): array; public function all(): array; ``` ### `faculty_repository` ```php local_uckk\local\faculty\faculty_repository ``` Responsabilités : ```text lire *.faculty.json valider le profil public résoudre la visibilité ne pas interroger les annonces ``` Méthodes : ```php public function get_by_slug(string $slug): array; public function get_by_faculty_id(string $facultyid): array; public function all_public(): array; ``` ## 14.4 Builder ```php local_uckk\local\faculty\faculty_page_builder ``` Responsabilités : ```text fusionner faculty profile + Atlas appliquer atlas_projection injecter dynamic block placeholders demander données publiques aux providers préparer un tableau exportable vers Mustache ne pas faire d’évaluation privée ne pas créer de cours ne pas modifier Moodle ``` Méthode canonique : ```php public function build(string $slug): array; ``` ## 14.5 Output class ```php local_uckk\output\faculty_page ``` Responsabilités : ```text recevoir le tableau construit implémenter export_for_template() préparer variables Mustache échapper/filtrer ce qui doit l’être ``` Template : ```text local_uckk/faculty_page ``` Fichier : ```text templates/faculty_page.mustache ``` --- # 15. Variables Mustache ## 15.1 Variables top-level Le template `faculty_page.mustache` reçoit uniquement : ```text page hero navigation identity sections atlas courses project_final limits relations dynamic_blocks featured_blocks faq contact notices metadata ``` ## 15.2 `page` ```json { "slug": "", "faculty_id": "", "voie_id": "", "status": "", "visibility": "", "seo_title": "", "seo_description": "", "canonical_url": "" } ``` ## 15.3 `hero` ```json { "eyebrow": "", "title": "", "subtitle": "", "summary": "", "primary_cta": {}, "secondary_cta": {} } ``` ## 15.4 `identity` ```json { "name": "", "short_name": "", "title_symbolique": "", "domain": "", "level": "", "faculty_role": "", "one_sentence": "" } ``` ## 15.5 `atlas` ```json { "definition_courte": "", "angle_fondamental": "", "competence_centrale": "", "seuils_progression": [], "show_definition_courte": true, "show_angle_fondamental": true, "show_competence_centrale": true, "show_seuils_progression": true } ``` ## 15.6 `courses` Chaque course card : ```json { "cours_id": "", "ordre": 1, "nom": "", "fullname": "", "concept_maitre_nom": "", "concept_maitre_definition": "", "artefact_type": "", "artefact_nom": "", "artefact_description": "", "moodle_url": "", "is_moodle_available": false } ``` Ne pas exposer dans la page publique par défaut : ```text concepts_associes criteres_passage notes participants completion status ``` ## 15.7 `dynamic_blocks` Chaque bloc : ```json { "id": "", "type": "", "title": "", "items": [], "has_items": false, "empty_state": "", "visibility": "public" } ``` Le template ne décide pas les permissions. Le provider doit filtrer avant export. --- # 16. Blocs dynamiques ## 16.1 Règle générale Un bloc dynamique ne stocke pas le contenu vivant dans le `*.faculty.json`. Il stocke : ```text type provider source limit visibility empty_state ``` Le contenu réel vient de Moodle ou de `local_uckk`. ## 16.2 Providers autorisés ### `moodle_forum` Usage : ```text annonces publiques nouvelles de la faculté messages épinglés ``` Source : ```json { "provider": "moodle_forum", "course_idnumber": "GJS-HUB", "forum_name": "Annonces" } ``` Règles : ```text Ne montrer que les discussions publiques. Ne montrer aucun message de forum de cours privé. Ne pas exposer les auteurs si le réglage public ne l’autorise pas. ``` ### `moodle_calendar` Usage : ```text événements rencontres publiques dates de présentation ``` Source : ```json { "provider": "moodle_calendar", "category_idnumber": "UCKK-GJS" } ``` Règles : ```text Ne montrer que les événements publics. Ne pas afficher événements privés d’utilisateur. ``` ### `moodle_category` Usage : ```text liste de cours Moodle associés ``` Source : ```json { "provider": "moodle_category", "category_idnumber": "UCKK-GJS" } ``` Règles : ```text Afficher seulement les cours visibles publiquement. Si un cours exige login, afficher une notice au lieu d’un lien direct d’inscription. ``` ### `local_uckk_news` Usage : ```text annonces éditoriales stockées dans local_uckk ``` Source : ```json { "provider": "local_uckk_news", "faculty_id": "faculty_grand_jeu_social" } ``` ### `local_uckk_manual` Usage : ```text blocs statiques contrôlés par JSON ``` Source : ```json { "provider": "local_uckk_manual" } ``` ### `none` Usage : ```text placeholder sans source active ``` Source : ```json { "provider": "none" } ``` ## 16.3 Types de blocs ### `announcements` Champs item : ```json { "title": "", "summary": "", "date": "", "url": "", "source_label": "" } ``` ### `events` Champs item : ```json { "title": "", "date_start": "", "date_end": "", "location": "", "url": "" } ``` ### `moodle_course_list` Champs item : ```json { "cours_id": "", "fullname": "", "summary": "", "url": "", "availability_label": "" } ``` ### `related_faculties` Champs item : ```json { "faculty_id": "", "slug": "", "name": "", "relation": "", "url": "" } ``` --- # 17. Sécurité publique ## 17.1 Données interdites en page publique Ne jamais afficher : ```text notes feedback privé progression individuelle achèvement individuel statut d’inscription individuel liste d’étudiants soumissions preuves privées votes privés rapports privés commentaires internes cas d’intégrité données Konnaxion personnelles ``` ## 17.2 Données autorisées Autorisé : ```text nom public de la faculté description publique programme de cours compétence centrale projet final limites éthiques relations intervoies annonces explicitement publiques événements explicitement publics cours visibles liens vers Moodle selon permissions note institutionnelle unique si nécessaire ``` ## 17.3 Filtrage Tout contenu texte issu des JSON doit passer par un filtre serveur approprié avant rendu. Règles : ```text Ne pas injecter HTML brut non filtré. Ne pas faire confiance au JSON comme HTML sûr. Ne pas rendre Markdown sans filtration. Ne pas construire d’URL sans validation. ``` ## 17.4 Retenue éditoriale publique Les pages publiques ne doivent pas répéter les limites de reconnaissance comme thème central. La règle éditoriale est : ```text une page publique doit ouvrir le savoir avant de limiter les attentes ``` La note institutionnelle courte peut apparaître une seule fois lorsque le contexte l’exige : ```text Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future. ``` Cette note ne doit pas être dupliquée dans : ```text la section héro les sections principales les blocs featured la FAQ les notices automatiques les garde-fous publics les cartes de cours ``` Sauf nécessité explicite, les pages doivent privilégier : ```text bibliothèque publique diffusion immédiate du savoir cadre d’apprentissage ouvert cours publics archives médiathèque assemblées défis méthodes praticables ``` --- # 18. Cache ## 18.1 Variables de cache | Variable | Valeur | | ----------------------- | ---------------------------------- | | `CACHE_FACULTY_PROFILE` | `local_uckk/faculty_profile` | | `CACHE_ATLAS_VOIE` | `local_uckk/atlas_voie` | | `CACHE_FACULTY_PAGE` | `local_uckk/faculty_page` | | `CACHE_DYNAMIC_BLOCK` | `local_uckk/faculty_dynamic_block` | ## 18.2 Clés de cache ```text faculty_profile:{slug}:{hash} atlas_voie:{voie_id}:{hash} faculty_page:{slug}:{atlas_hash}:{faculty_hash} dynamic_block:{slug}:{block_id}:{provider}:{hash} ``` ## 18.3 Source hash Chaque fichier lu doit produire un hash : ```text sha256(file contents) ``` Variables : ```text atlas_source_hash faculty_source_hash merged_page_hash ``` ## 18.4 Invalidation Vider cache quand : ```text un voie_*.json change un *.faculty.json change faculty_manifest.json change atlas_manifest.json change un réglage local_uckk lié aux pages change un provider dynamique demande refresh ``` --- # 19. Sync Moodle ## 19.1 Mode lecture seule Par défaut : ```text Faculty page generation = read-only ``` Aucun cours, badge ou champ custom n’est créé pendant une visite publique. ## 19.2 Mode dry-run Commande ou écran admin : ```text tool_uckkseed / local_uckk atlas sync dry-run ``` Le dry-run produit : ```text catégories à créer catégories à mettre à jour cours à créer cours à mettre à jour champs custom manquants badges à créer diffs de hash erreurs de validation ``` ## 19.3 Mode apply Autorisé uniquement via admin Moodle ou outil seed avec capability. Ne jamais lancer depuis une page publique. ## 19.4 Statuts sync Allowed values : ```text not_synced in_sync changed_in_json changed_in_moodle conflict missing_in_moodle missing_in_json sync_error ``` ## 19.5 Conflict rule Si Moodle a été modifié manuellement et que le JSON a changé : ```text status = conflict ne pas écraser automatiquement produire un rapport demander décision admin ``` --- # 20. Capabilities ## 20.1 Capabilities nouvelles proposées | Variable | Capability | Usage | | ------------------------------ | ---------------------------------- | ---------------------------------------------- | | `CAP_VIEW_PUBLIC_FACULTIES` | `local/uckk:viewpublicfaculties` | Voir pages publiques restreintes si nécessaire | | `CAP_MANAGE_FACULTY_PROFILES` | `local/uckk:managefacultyprofiles` | Gérer profils publics de faculté | | `CAP_VALIDATE_ATLAS_JSON` | `local/uckk:validateatlasjson` | Lancer validation Atlas | | `CAP_SYNC_ATLAS_MOODLE` | `local/uckk:syncatlasmoodle` | Lancer dry-run/apply sync Moodle | | `CAP_VIEW_FACULTY_SYNC_REPORT` | `local/uckk:viewfacultysyncreport` | Voir rapport de sync | | `CAP_PURGE_FACULTY_CACHE` | `local/uckk:purgefacultycache` | Purger cache pages facultés | ## 20.2 Règles ```text Les visiteurs anonymes peuvent voir visibility=public. Les pages restricted exigent require_login(). Les actions admin exigent capability. Aucun symbolic title ne donne permission. ``` --- # 21. Événements ## 21.1 Événements proposés | Variable | Event class | Quand | | ----------------------------------- | ---------------------------------------------- | ---------------------------------------- | | `EVENT_FACULTY_PROFILE_VIEWED` | `local_uckk\event\faculty_profile_viewed` | page faculty consultée si logging activé | | `EVENT_FACULTY_PROFILE_VALIDATED` | `local_uckk\event\faculty_profile_validated` | validation admin | | `EVENT_ATLAS_VOIE_VALIDATED` | `local_uckk\event\atlas_voie_validated` | validation d’un JSON Atlas | | `EVENT_ATLAS_SYNC_DRYRUN_COMPLETED` | `local_uckk\event\atlas_sync_dryrun_completed` | dry-run terminé | | `EVENT_ATLAS_SYNC_APPLIED` | `local_uckk\event\atlas_sync_applied` | sync appliquée | | `EVENT_FACULTY_CACHE_PURGED` | `local_uckk\event\faculty_cache_purged` | cache purgé | ## 21.2 Règles ```text Ne pas logger de données privées dans description. Ne pas logger tout le contenu JSON. Logger seulement ids, status, counts, hashes. ``` --- # 22. Services ## 22.1 Services internes PHP ```text local_uckk\local\atlas\voie_repository local_uckk\local\atlas\voie_validator local_uckk\local\atlas\voie_normalizer local_uckk\local\atlas\voie_moodle_mapper local_uckk\local\faculty\faculty_registry local_uckk\local\faculty\faculty_repository local_uckk\local\faculty\faculty_validator local_uckk\local\faculty\faculty_normalizer local_uckk\local\faculty\faculty_page_builder local_uckk\local\faculty\faculty_dynamic_block_provider local_uckk\local\faculty\faculty_moodle_mapper ``` ## 22.2 Services externes optionnels Ne pas exposer tant que non nécessaire. Si exposés : ```text local_uckk_validate_faculty_profile local_uckk_validate_atlas_voie local_uckk_get_faculty_public_page local_uckk_get_faculty_sync_report local_uckk_run_atlas_sync_dryrun ``` Règles : ```text Chaque service externe exige db/services.php. Chaque service externe exige classes/external/*. Chaque service externe valide paramètres et retours. Chaque service externe vérifie capabilities. ``` --- # 23. Templates ## 23.1 Template principal ```text templates/faculty_page.mustache ``` Rôle : ```text shell global de page faculté aucune logique métier aucun appel DB aucune décision de permission aucun fallback de sécurité ``` ## 23.2 Partials ```text templates/faculty_hero.mustache templates/faculty_navigation.mustache templates/faculty_sections.mustache templates/faculty_atlas_projection.mustache templates/faculty_course_card.mustache templates/faculty_dynamic_block.mustache templates/faculty_notice.mustache templates/faculty_faq.mustache templates/faculty_contact.mustache ``` ## 23.3 Règle anti-variable sauvage Si un template utilise : ```mustache {{new_variable}} ``` alors `new_variable` doit être documentée ici dans la section variables Mustache avant commit. --- # 24. Lang strings ## 24.1 Composant ```text lang/fr/local_uckk.php lang/en/local_uckk.php ``` ## 24.2 Strings minimales ```php $string['faculty'] = 'Faculté'; $string['faculties'] = 'Facultés'; $string['facultyprofile'] = 'Profil public de faculté'; $string['facultyatlasprogram'] = 'Programme de la Voie'; $string['facultycourses'] = 'Cours publics'; $string['facultyannouncements'] = 'Annonces de la voie'; $string['facultyevents'] = 'Événements publics'; $string['facultyprojectfinal'] = 'Projet final'; $string['facultyethicallimits'] = 'Limites éthiques'; $string['facultyrelations'] = 'Relations avec les autres Voies'; $string['internalrecognitionnotice'] = 'Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future.'; $string['publicknowledgeframework'] = 'Bibliothèque publique et cadre d’apprentissage ouvert'; $string['openknowledgeaccess'] = 'Accès public au savoir'; $string['faculty_ai_public_name'] = 'Voie de la Production augmentée par l’IA'; $string['faculty_ai_short_name'] = 'Production IA'; $string['faculty_ai_editorial_short_name'] = 'Production augmentée'; $string['faculty_ai_symbolic_title'] = 'Maître d’œuvre augmenté'; $string['faculty_ai_domain'] = 'Production outillée'; $string['faculty_ai_public_formula'] = 'Utiliser l’IA pour écrire, concevoir, coder, documenter, créer, accompagner, vérifier et produire des œuvres, outils et systèmes utiles, sans déléguer le jugement humain.'; ``` Règles : ```text Ne pas hardcoder les labels publics dans PHP. Ne pas traduire les IDs. Ne pas traduire les slugs. Ne pas répéter la note de reconnaissance dans plusieurs chaînes publiques. ``` --- # 25. Style public ## 25.1 Classes CSS racine ```text .local-uckk-faculty .local-uckk-faculty-hero .local-uckk-faculty-nav .local-uckk-faculty-section .local-uckk-faculty-course-card .local-uckk-faculty-dynamic-block .local-uckk-faculty-notice .local-uckk-faculty-faq ``` ## 25.2 Interdictions Ne pas utiliser : ```text .faculty .course-card .hero .card ``` sans préfixe `local-uckk-`. ## 25.3 Règle Le thème peut styliser, mais ne doit pas porter la logique. ```text theme_uckk = présentation local_uckk = données et rendu public tool_uckkseed = sync/presets ``` --- # 26. Validation JSON ## 26.1 Validation Atlas Chaque `voie_*.json` doit valider : ```text JSON syntax valid schema_version = UCKK-ATLAS-0.2-draft voie_id matches manifest code matches manifest 10 courses course ids match prefix orders 1..10 concept_maitre exists concept_maitre.type = concept_maitre concepts_associes array all concepts_associes have type concept_associe all notions_fines are arrays artefact_maitrise exists criteres_passage non-empty projet_final exists limites_ethiques non-empty relations_intervoies references valid voie_id tags array ``` ## 26.2 Validation Faculty Chaque `*.faculty.json` doit valider : ```text JSON syntax valid schema_version = UCKK-FACULTY-0.1 faculty_id matches manifest voie_id references valid Atlas file slug matches manifest source_atlas.file exists moodle.category_idnumber matches manifest moodle.course_prefix matches Atlas code identity fields present seo fields present hero fields present navigation targets exist sections have unique ids atlas_projection complete dynamic_blocks providers allowed featured_blocks types allowed faq valid governance metadata valid public_claims_guardrails optional and non-repetitive when present credential-oriented wording limited to one quiet institutional note when necessary cache config valid ``` ## 26.3 Cross-file validation Le validateur doit vérifier : ```text faculty.voie_id == atlas.voie_id faculty.moodle.course_prefix == atlas.code faculty.identity.title_symbolique == atlas.titre_symbolique unless override declared faculty.identity.domain == atlas.domaine_operatoire unless override declared faculty.identity.level == atlas.niveau_vise faculty.source_atlas.file points to actual atlas file faculty.slug unique faculty_id unique category_idnumber unique course_prefix unique relations_intervoies point to valid voie_id ``` --- # 27. Variables d’override ## 27.1 Règle générale Un override doit être explicite. Structure : ```json { "overrides": { "identity.title_symbolique": { "enabled": true, "reason": "Titre public simplifié", "source_value": "Joueur lucide", "public_value": "Joueur lucide" } } } ``` ## 27.2 Overrides autorisés ```text identity.name identity.short_name identity.title_symbolique identity.domain hero.title hero.subtitle seo.title seo.description ``` ## 27.3 Overrides interdits ```text voie_id faculty_id slug source_atlas.file cours_id concept_id schema_version category_idnumber course_prefix ``` --- # 28. Exemple minimal complet de `*.faculty.json` ```json { "schema_version": "UCKK-FACULTY-0.1", "faculty_id": "faculty_grand_jeu_social", "voie_id": "voie_grand_jeu_social", "slug": "grand-jeu-social", "status": "published", "visibility": "public", "source_atlas": { "file": "voie_grand_jeu_social.json", "schema_version_expected": "UCKK-ATLAS-0.2-draft", "sync_mode": "read_only" }, "moodle": { "category_id": null, "category_idnumber": "UCKK-GJS", "course_prefix": "GJS", "public_course_listing": true, "enrolment_visibility": "public_info_only", "hub_course_idnumber": "GJS-HUB" }, "identity": { "eyebrow": "Voie fondatrice UCKK", "name": "Voie du Grand Jeu social", "short_name": "Grand Jeu social", "title_symbolique": "Joueur lucide", "domain": "Systèmes sociaux", "level": "Puissance opératoire", "faculty_role": "Voie transversale mère de l’Atlas conceptuel UCKK.", "one_sentence": "Lire les règles, pouvoirs, récits, preuves, ressources et transformations du monde social." }, "seo": { "title": "Voie du Grand Jeu social — UCKK", "description": "La Voie du Grand Jeu social ouvre un cadre public d’apprentissage pour lire les systèmes sociaux, comprendre les règles du jeu et agir avec intégrité.", "keywords": [ "UCKK", "Grand Jeu social", "systèmes sociaux", "pouvoir", "institutions", "récits", "preuves" ] }, "hero": { "title": "Voie du Grand Jeu social", "subtitle": "Lire les systèmes, comprendre les règles du jeu, agir avec lucidité.", "summary": "Cette faculté ouvre une bibliothèque publique et un cadre d’apprentissage pour cartographier les règles visibles et invisibles, les positions, les pouvoirs, les récits, les preuves, les ressources et les points de transformation d’un système social.", "primary_cta": { "label": "Explorer les cours publics", "target": "#cours" }, "secondary_cta": { "label": "Voir l’Atlas des Voies", "target": "/local/uckk/programs.php" } }, "navigation": [ { "label": "Présentation", "target": "#presentation" }, { "label": "Programme", "target": "#programme" }, { "label": "Cours", "target": "#cours" }, { "label": "Projet final", "target": "#projet-final" }, { "label": "Annonces", "target": "#annonces" } ], "sections": [ { "id": "presentation", "type": "text", "title": "Une faculté pour lire le jeu avant d’y jouer", "body": "La Voie du Grand Jeu social sert de matrice transversale aux autres Voies UCKK. Elle donne une grammaire pour lire les règles, institutions, récits, pouvoirs, langages, preuves, ressources, comportements et possibilités de transformation." }, { "id": "pourquoi", "type": "text", "title": "Pourquoi cette Voie existe", "body": "Les sociétés ne sont pas seulement des ensembles d’individus. Elles sont aussi des systèmes de positions, de contraintes, de scènes publiques, de statuts, d’accès, de récits et de preuves." } ], "atlas_projection": { "show_definition_courte": true, "show_angle_fondamental": true, "show_competence_centrale": true, "show_seuils_progression": true, "show_courses": true, "show_course_codes": true, "show_concept_maitre": true, "show_concepts_associes": false, "show_artefacts": true, "show_criteres_passage": false, "show_projet_final": true, "show_limites_ethiques": true, "show_relations_intervoies": true, "show_tags": false }, "dynamic_blocks": [ { "id": "annonces", "type": "announcements", "title": "Annonces de la faculté", "source": { "provider": "moodle_forum", "course_idnumber": "GJS-HUB", "forum_name": "Annonces" }, "limit": 5, "visibility": "public", "empty_state": "Aucune annonce publique pour le moment." }, { "id": "cours-moodle", "type": "moodle_course_list", "title": "Cours associés", "source": { "provider": "moodle_category", "category_idnumber": "UCKK-GJS" }, "limit": 20, "visibility": "public", "empty_state": "Les cours Moodle associés seront affichés ici lorsqu’ils seront disponibles." } ], "featured_blocks": [ { "type": "principle", "title": "Principe central", "body": "Voir le jeu comme jeu ne sert pas à manipuler : cela sert à agir avec plus de responsabilité." }, { "type": "notice", "title": "Bibliothèque publique", "body": "Le but immédiat de cette page est de rendre le savoir accessible dans un cadre d’apprentissage ouvert, familier et modernisé." } ], "faq": [ { "question": "Cette Voie est-elle obligatoire?", "answer": "Elle peut servir de tronc de lecture commun, car elle fournit la grammaire générale du Grand Jeu social." }, { "question": "Quel est le but immédiat de cette Voie?", "answer": "Le but immédiat est la diffusion publique du savoir dans un cadre d’apprentissage ouvert. Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future." } ], "contact": { "label": "Contact", "body": "Pour toute question sur cette Voie, consultez les annonces publiques ou les espaces Moodle associés.", "email": "", "cta": { "label": "Voir les annonces", "target": "#annonces" } }, "governance": { "owner": "local_uckk", "editorial_status": "approved", "last_reviewed": null, "review_notes": "", "public_claims_guardrails": [ "Garder la note de reconnaissance unique, discrète et non centrale; ne pas transformer la page publique en avertissement répété sur les diplômes ou statuts." ] }, "cache": { "enabled": true, "ttl_seconds": 3600 } } ``` --- # 29. Tests obligatoires ## 29.1 Tests unitaires ```text voie_repository loads all 10 JSON files voie_validator rejects invalid schema_version voie_validator rejects missing concept_maitre.type voie_validator rejects non-array notions_fines voie_validator rejects invalid relation voie_id faculty_registry resolves all 10 slugs faculty_repository loads all 10 faculty profiles faculty_validator rejects unknown provider faculty_validator rejects orphan navigation targets faculty_page_builder builds all 10 pages faculty_page_builder applies atlas_projection dynamic_block_provider filters public data moodle_mapper maps course ids correctly ``` ## 29.2 Tests Behat ```text anonymous user opens published faculty page anonymous user cannot open hidden faculty page anonymous user sees open public knowledge framing anonymous user does not see repeated credential/accreditation caveats institutional recognition note appears at most once when required anonymous user sees 10 courses from Atlas projection anonymous user does not see private completion status logged-in user sees allowed Moodle links unknown slug returns safe 404 faculty page renders empty dynamic blocks safely ``` ## 29.3 Tests de fichiers ```text All JSON files validate. All PHP files pass php -l. All Mustache templates use documented variables only. No template contains business logic. No public page accepts file path from request. ``` --- # 30. Règles IA anti-drift ## 30.1 Ne jamais inventer ces éléments Une IA ne doit pas inventer : ```text nouveau slug nouveau voie_id nouveau faculty_id nouveau course prefix nouveau provider nouveau dynamic block type nouveau template variable nouveau custom field nouvelle capability nouvel event nouveau service ``` sans l’ajouter explicitement à ce document. ## 30.2 Ne jamais confondre ```text Faculty Profile ≠ Atlas Voie Atlas Voie ≠ Moodle course Moodle category ≠ faculty JSON Parchemin ≠ diplôme public Dynamic block ≠ static section Provider ≠ template Template ≠ permission layer Slug ≠ file path voie_ia_gouvernable = identifiant technique Voie de la Production augmentée par l’IA = nom public Production IA = nom court public Maître d’œuvre augmenté = titre symbolique public IA comme outil de production ≠ IA comme autorité ``` ## 30.3 Règle de génération Avant de générer un fichier, l’IA doit identifier : ```text 1. Le composant Moodle propriétaire. 2. Le chemin exact. 3. Le schéma applicable. 4. Les variables déjà documentées. 5. Les sources de données autorisées. 6. Les données interdites. 7. Les tests associés. ``` ## 30.4 Règle de modification Avant de modifier un JSON : ```text Valider le manifest. Valider le schéma. Vérifier les IDs. Vérifier les slugs. Vérifier les relations. Vérifier les provider names. Vérifier les règles de retenue éditoriale publique. ``` ## 30.5 Règle de sortie Une IA qui produit du code doit produire aussi : ```text fichiers modifiés variables utilisées nouveaux champs éventuels tests à exécuter risques anti-drift ``` --- # 31. Définition de complétion L’extension est complète lorsque les éléments suivants existent et sont cohérents : ```text [ ] local/uckk/atlas/atlas_manifest.json [ ] local/uckk/atlas/atlas_schema.json [ ] local/uckk/atlas/voies/ contient les 10 voie_*.json [ ] local/uckk/content/faculties/faculty_manifest.json [ ] local/uckk/content/faculties/faculty_schema.json [ ] local/uckk/content/faculties/ contient les 10 *.faculty.json [ ] local/uckk/faculty.php existe [ ] faculty.php résout uniquement les slugs autorisés [ ] voie_repository lit les 10 JSON Atlas [ ] voie_validator valide les 10 JSON Atlas [ ] faculty_repository lit les 10 Faculty Profiles [ ] faculty_validator valide les 10 Faculty Profiles [ ] faculty_page_builder fusionne Atlas + Faculty + dynamique [ ] templates/faculty_page.mustache existe [ ] tous les partials faculty_* existent [ ] les templates n’utilisent aucune variable non documentée [ ] les pages publiques affichent les 10 cours [ ] les pages publiques foregroundent la bibliothèque publique, les cours ouverts et la diffusion du savoir [ ] la note institutionnelle de reconnaissance apparaît au maximum une fois lorsque nécessaire [ ] les pages publiques n’affichent aucune donnée privée [ ] les blocs dynamiques échouent proprement si Moodle ne contient aucune annonce [ ] dry-run sync Moodle produit un rapport sans modifier la DB [ ] apply sync Moodle est protégé par capability [ ] cache peut être purgé [ ] tests PHPUnit et Behat couvrent la fonctionnalité ``` --- # 32. Résumé exécutable ```text Créer une couche Faculty Profile normalisée. Garder les JSON Atlas comme source canonique pédagogique. Garder Moodle comme source opérationnelle. Générer les pages publiques en fusionnant Atlas + Faculty Profile + blocs dynamiques filtrés. Ne jamais écrire dans Moodle depuis une page publique. Ne jamais exposer de données privées. Ne jamais inventer un champ non documenté. Ne jamais présenter les Parchemins comme diplômes publics. Ne jamais confondre page de faculté et cours Moodle. Ne jamais utiliser un slug comme chemin de fichier. Ne jamais transformer les pages publiques en répétition défensive sur l’accréditation. Ne jamais présenter la Voie IA comme une délégation du contrôle à l’IA; la présenter comme une voie de production augmentée sous responsabilité humaine. ``` Formule finale : ```text Atlas définit. Faculty Profile raconte. Moodle exécute. local_uckk relie. Mustache affiche. La page publique ouvre le savoir. L’IA ne renomme rien. ``` ================================================================================================ FILE: docs/13_faculty_json_authoring_guide.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 771c9744ea9b92814a2cf1b1e46f8c62690fea0357bfcc8516bcd7e400fad69e CONTENT_BYTES: 57174 ================================================================================================ # DOC_13 — UCKK Faculty JSON Authoring Guide **Document canonique proposé :** `docs/13_faculty_json_authoring_guide.md` **Composant principal :** `local_uckk` **Portée :** guide de rédaction, édition, révision et validation des fichiers `*.faculty.json`. **Dépendance normative :** `docs/12_faculty_pages_atlas_public_contract.md` **Statut :** guide d’auteur pour les profils publics de facultés. **Version :** `UCKK-FACULTY-AUTHORING-GUIDE-0.2` **Schéma cible :** `UCKK-FACULTY-0.1` **Chemin des profils :** `local/uckk/content/faculties/` --- # 1. Objet Ce document explique comment rédiger les fichiers JSON publics de faculté : ```text local/uckk/content/faculties/*.faculty.json ``` Ces fichiers ne sont pas les programmes pédagogiques complets. Ils sont les profils éditoriaux publics des facultés UCKK. Leur fonction principale est de présenter chaque Voie comme une porte d’entrée publique dans l’Univers-Cité King Klown : une bibliothèque vivante, un cadre d’apprentissage ouvert et un espace de lecture, d’orientation, de méthode et de pratique du savoir. Formule de travail : ```text Atlas JSON = ce qui est enseigné. Faculty JSON = comment la faculté se présente publiquement. Moodle = activité réelle, cours, annonces, calendrier, inscriptions, achèvements. local_uckk = lecture, validation, fusion, rendu, synchronisation. ``` Un `*.faculty.json` doit donc : ```text présenter publiquement une faculté; référencer son JSON Atlas; choisir quoi projeter depuis l’Atlas; définir la structure éditoriale de la page; configurer les blocs dynamiques publics; mettre en avant l’accès au savoir, la lisibilité et la pratique; orienter vers les cours publics disponibles; respecter les règles publiques UCKK; ne jamais exposer de données privées Moodle. ``` Règle éditoriale centrale : ```text La page publique ouvre le savoir avant de limiter les attentes. ``` --- # 2. Fichiers concernés Les fichiers éditoriaux publics sont : ```text local/uckk/content/faculties/grand-jeu-social.faculty.json local/uckk/content/faculties/economie.faculty.json local/uckk/content/faculties/ecologie.faculty.json local/uckk/content/faculties/sciences-politiques.faculty.json local/uckk/content/faculties/linguistique-architecture-du-sens.faculty.json local/uckk/content/faculties/metaphysique.faculty.json local/uckk/content/faculties/ia-gouvernable.faculty.json local/uckk/content/faculties/intervention-sociale-systemes-humains.faculty.json local/uckk/content/faculties/architecture-sociotechnique.faculty.json local/uckk/content/faculties/ecosysteme-digital-koa.faculty.json ``` Ils sont listés par : ```text local/uckk/content/faculties/faculty_manifest.json ``` Ils sont validés par : ```text local/uckk/content/faculties/faculty_schema.json local/uckk/classes/local/faculty/faculty_validator.php ``` --- # 3. Règle principale de non-duplication Un profil `*.faculty.json` ne doit pas recopier les cours Atlas complets. Interdit : ```json { "courses": [ { "cours_id": "GJS101", "nom": "Cartographie du Grand Jeu social", "concepts_associes": [] } ] } ``` Autorisé : ```json { "atlas_projection": { "show_courses": true, "show_course_codes": true, "show_concept_maitre": true, "show_concepts_associes": false } } ``` Le contenu pédagogique canonique reste dans : ```text local/uckk/atlas/voies/voie_*.json ``` Le contenu éditorial public reste dans : ```text local/uckk/content/faculties/*.faculty.json ``` La page publique ne doit pas expliquer la mécanique interne avec des phrases comme : ```text projeté depuis le JSON Atlas; dérivé de l’Atlas; espaces Moodle visibles associés au préfixe; préfixe IA, AS, ECL, etc. ``` Ces détails peuvent exister dans les champs techniques, mais ils ne doivent pas devenir du texte public. --- # 4. Workflow auteur Pour créer ou modifier un profil de faculté : ```text 1. Identifier la faculté dans le tableau canonique. 2. Vérifier le voie_id, faculty_id, slug, code, course_prefix. 3. Vérifier le fichier Atlas référencé. 4. Conserver les identifiants techniques stables. 5. Rédiger le nom public, le nom court, le titre symbolique et le domaine. 6. Rédiger identity, seo, hero, sections, faq et contact en langage public. 7. Définir atlas_projection sans dupliquer les données Atlas. 8. Configurer les dynamic_blocks seulement avec des providers autorisés. 9. Orienter les CTA vers les cours, les annonces ou les sections utiles. 10. Vérifier que la note de reconnaissance n’est pas répétée. 11. Valider le JSON. 12. Vérifier que les targets de navigation ne sont pas orphelines. ``` --- # 5. Tableau canonique des facultés | Ordre | `voie_id` | `faculty_id` | `slug` | `code` | `course_prefix` | `category_idnumber` | `atlas_file` | `faculty_file` | Nom public recommandé | | ----: | --- | --- | --- | --- | --- | --- | --- | --- | --- | | 1 | `voie_grand_jeu_social` | `faculty_grand_jeu_social` | `grand-jeu-social` | `GJS` | `GJS` | `UCKK-GJS` | `voie_grand_jeu_social.json` | `grand-jeu-social.faculty.json` | Voie du Grand Jeu social | | 2 | `voie_economie` | `faculty_economie` | `economie` | `EC` | `EC` | `UCKK-EC` | `voie_economie.json` | `economie.faculty.json` | Voie d’Économie | | 3 | `voie_ecologie` | `faculty_ecologie` | `ecologie` | `ECL` | `ECL` | `UCKK-ECL` | `voie_ecologie.json` | `ecologie.faculty.json` | Voie d’Écologie | | 4 | `voie_sciences_politiques` | `faculty_sciences_politiques` | `sciences-politiques` | `SP` | `SP` | `UCKK-SP` | `voie_sciences_politiques.json` | `sciences-politiques.faculty.json` | Voie des Sciences politiques | | 5 | `voie_linguistique_architecture_du_sens` | `faculty_linguistique_architecture_du_sens` | `linguistique-architecture-du-sens` | `LI` | `LI` | `UCKK-LI` | `voie_linguistique_architecture_du_sens.json` | `linguistique-architecture-du-sens.faculty.json` | Voie de la Linguistique et de l’architecture du sens | | 6 | `voie_metaphysique` | `faculty_metaphysique` | `metaphysique` | `ME` | `ME` | `UCKK-ME` | `voie_metaphysique.json` | `metaphysique.faculty.json` | Voie de la Métaphysique | | 7 | `voie_ia_gouvernable` | `faculty_ia_gouvernable` | `ia-gouvernable` | `IA` | `IA` | `UCKK-IA` | `voie_ia_gouvernable.json` | `ia-gouvernable.faculty.json` | Voie de la Production augmentée par l’IA | | 8 | `voie_intervention_sociale_systemes_humains` | `faculty_intervention_sociale_systemes_humains` | `intervention-sociale-systemes-humains` | `IS` | `IS` | `UCKK-IS` | `voie_intervention_sociale_systemes_humains.json` | `intervention-sociale-systemes-humains.faculty.json` | Voie de l’Intervention sociale et des systèmes humains | | 9 | `voie_architecture_sociotechnique` | `faculty_architecture_sociotechnique` | `architecture-sociotechnique` | `AS` | `AS` | `UCKK-AS` | `voie_architecture_sociotechnique.json` | `architecture-sociotechnique.faculty.json` | Voie d’Architecture sociotechnique | | 10 | `voie_ecosysteme_digital_koa` | `faculty_ecosysteme_digital_koa` | `ecosysteme-digital-koa` | `KOA` | `KOA` | `UCKK-KOA` | `voie_ecosysteme_digital_koa.json` | `ecosysteme-digital-koa.faculty.json` | Voie de l’Architecture de l’écosystème digital kOA | ## 5.1 Convention spéciale pour la Voie IA Les identifiants techniques restent stables : ```text voie_id = voie_ia_gouvernable faculty_id = faculty_ia_gouvernable slug = ia-gouvernable code = IA course_prefix = IA category_idnumber = UCKK-IA hub_course_idnumber = IA-HUB atlas_file = voie_ia_gouvernable.json faculty_file = ia-gouvernable.faculty.json ``` Mais le nom public recommandé change : ```text Nom public : Voie de la Production augmentée par l’IA Nom court : Production IA Nom court éditorial : Production augmentée Titre symbolique : Maître d’œuvre augmenté Domaine : Production outillée ``` Règle éditoriale : ```text Ne pas présenter cette Voie comme une délégation du contrôle à l’IA. Présenter l’IA comme outil de production, de création, de code, de documentation, d’accompagnement, de vérification et de prototypage. La responsabilité, la décision et l’autorité finale demeurent humaines. ``` --- # 6. Squelette complet d’un profil Faculty JSON Ce squelette montre la structure complète attendue. Les valeurs doivent être adaptées à chaque faculté canonique. ```json { "schema_version": "UCKK-FACULTY-0.1", "faculty_id": "faculty_grand_jeu_social", "voie_id": "voie_grand_jeu_social", "slug": "grand-jeu-social", "status": "published", "visibility": "public", "source_atlas": { "file": "voie_grand_jeu_social.json", "schema_version_expected": "UCKK-ATLAS-0.2-draft", "sync_mode": "read_only" }, "moodle": { "category_id": null, "category_idnumber": "UCKK-GJS", "course_prefix": "GJS", "public_course_listing": true, "enrolment_visibility": "public_info_only", "hub_course_idnumber": "GJS-HUB" }, "identity": { "eyebrow": "Voie UCKK", "name": "Voie du Grand Jeu social", "short_name": "Grand Jeu social", "title_symbolique": "Joueur lucide", "domain": "Systèmes sociaux", "level": "Puissance opératoire", "faculty_role": "Voie qui ouvre une grammaire publique pour lire la société comme un système de règles, d’acteurs, de pouvoirs, de récits, de preuves, de ressources et de transformations possibles.", "one_sentence": "Lire les règles, les positions, les pouvoirs, les récits, les preuves et les ressources du Grand Jeu social afin d’agir avec plus de lucidité." }, "seo": { "title": "Voie du Grand Jeu social — UCKK", "description": "Présentation publique de la Voie du Grand Jeu social dans l’Univers-Cité King Klown : repères, cours, méthodes et pratiques pour comprendre le Grand Jeu social.", "keywords": [ "UCKK", "Voie", "Grand Jeu social", "bibliothèque publique", "puissance opératoire" ] }, "hero": { "title": "Voie du Grand Jeu social", "subtitle": "Lire les systèmes, comprendre les règles du jeu, agir avec lucidité.", "summary": "Cette voie fait partie de l’Univers-Cité King Klown : un établissement virtuel de puissance opératoire consacré au Grand Jeu social. Elle rassemble des cours publics, des repères, des méthodes et des exercices pour apprendre à lire un domaine, agir avec lucidité et construire des preuves de compréhension.", "primary_cta": { "label": "Comprendre la voie", "target": "#programme" }, "secondary_cta": { "label": "Accéder aux cours", "target": "#cours-moodle" } }, "navigation": [ { "label": "Présentation", "target": "#presentation" }, { "label": "Parcours", "target": "#programme" }, { "label": "Cours", "target": "#cours-moodle" }, { "label": "Projet final", "target": "#projet-final" }, { "label": "Éthique", "target": "#ethique" }, { "label": "Annonces", "target": "#annonces" } ], "sections": [ { "id": "presentation", "type": "text", "title": "Une voie pour lire le jeu avant d’y jouer", "body": "Cette faculté présente une Voie UCKK comme parcours public de lecture, de méthode et de pratique dans la bibliothèque vivante de l’Univers-Cité King Klown." }, { "id": "programme", "type": "text", "title": "Parcours de la Voie", "body": "Cette voie organise un parcours public de lecture, de méthode et de pratique. Elle aide à comprendre un domaine du Grand Jeu social, à reconnaître ses règles visibles et invisibles, puis à développer des capacités d’action plus lucides, responsables et vérifiables." }, { "id": "cours", "type": "callout", "title": "Explorer les cours publics", "body": "Les cours publics sont les principales portes d’entrée dans cette voie. Ils permettent de découvrir les concepts, méthodes, exercices et artefacts d’apprentissage, puis d’ouvrir l’espace de cours correspondant lorsqu’il est disponible." }, { "id": "projet-final", "type": "text", "title": "Projet final", "body": "Le projet final permet de produire une trace opératoire : carte, dossier, prototype, analyse, méthode, intervention, système documentaire ou artefact public démontrant la compréhension de la voie." }, { "id": "ethique", "type": "notice", "title": "Éthique publique", "body": "La puissance opératoire visée doit rester lisible, contestable, responsable et compatible avec l’intégrité des personnes concernées." } ], "atlas_projection": { "show_definition_courte": true, "show_angle_fondamental": true, "show_competence_centrale": true, "show_seuils_progression": true, "show_courses": true, "show_course_codes": true, "show_concept_maitre": true, "show_concepts_associes": false, "show_artefacts": true, "show_criteres_passage": false, "show_projet_final": true, "show_limites_ethiques": true, "show_relations_intervoies": true, "show_tags": false }, "dynamic_blocks": [ { "id": "annonces", "type": "announcements", "title": "Annonces de la voie", "source": { "provider": "moodle_forum", "course_idnumber": "GJS-HUB", "forum_name": "Annonces" }, "limit": 5, "visibility": "public", "empty_state": "Aucune annonce publique pour le moment." }, { "id": "cours-moodle", "type": "moodle_course_list", "title": "Accéder aux cours", "source": { "provider": "moodle_category", "category_idnumber": "UCKK-GJS" }, "limit": 10, "visibility": "public", "empty_state": "Les cours publics de cette voie seront affichés ici lorsqu’ils seront disponibles." } ], "featured_blocks": [ { "type": "principle", "title": "Voir le jeu avant de jouer", "body": "Toute action responsable commence par la lecture des règles, des positions, des ressources, des récits et des preuves qui structurent une situation." }, { "type": "method", "title": "Pratiquer avec méthode", "body": "Une Voie UCKK sert à transformer des savoirs en repères praticables, en exercices, en cartes et en artefacts vérifiables." }, { "type": "ethics", "title": "Agir avec responsabilité", "body": "La puissance opératoire ne doit pas devenir opacité, domination ou manipulation. Elle doit rester lisible, contestable et responsable." } ], "faq": [ { "question": "Par où commencer?", "answer": "Commencez par la présentation de la voie, puis ouvrez les cours publics disponibles. Chaque cours sert de porte d’entrée vers une notion, une méthode ou un artefact d’apprentissage." }, { "question": "Faut-il être inscrit pour apprendre?", "answer": "Les pages publiques donnent accès aux repères essentiels de la voie. Certains espaces de cours peuvent demander une connexion ou une inscription selon leur usage, mais l’orientation générale du savoir reste publique." }, { "question": "Que signifie le titre symbolique associé à cette Voie?", "answer": "C’est un repère narratif et pédagogique interne. Il aide à nommer une posture d’apprentissage ou de pratique. Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future." } ], "contact": { "label": "Contact", "body": "Pour suivre cette voie, commencez par les cours disponibles, puis consultez les annonces publiques pour les nouvelles, rencontres et ouvertures d’espaces d’apprentissage.", "email": "", "cta": { "label": "Voir les annonces", "target": "#annonces" } }, "governance": { "owner": "local_uckk", "editorial_status": "approved", "last_reviewed": null, "review_notes": "", "public_claims_guardrails": [ "Garder la note de reconnaissance unique, discrète et non centrale; ne pas transformer la page publique en avertissement répété sur les diplômes, statuts ou certifications." ] }, "cache": { "enabled": true, "ttl_seconds": 3600 } } ``` --- # 7. Champs top-level obligatoires Chaque profil doit contenir exactement les familles de champs suivantes : ```json { "schema_version": "UCKK-FACULTY-0.1", "faculty_id": "", "voie_id": "", "slug": "", "status": "draft", "visibility": "hidden", "source_atlas": {}, "moodle": {}, "identity": {}, "seo": {}, "hero": {}, "navigation": [], "sections": [], "atlas_projection": {}, "dynamic_blocks": [], "featured_blocks": [], "faq": [], "contact": {}, "governance": {}, "cache": {} } ``` Règles : ```text Aucun champ obligatoire ne doit être omis. Aucun champ structurel ne doit changer de type. Les listes vides doivent rester des listes. Les objets vides doivent rester des objets. Ne pas utiliser null pour remplacer une liste. ``` --- # 8. `schema_version` Valeur obligatoire : ```json "schema_version": "UCKK-FACULTY-0.1" ``` Interdit : ```json "schema_version": "1.0" ``` ```json "schema_version": "faculty" ``` ```json "schema_version": null ``` --- # 9. `faculty_id`, `voie_id`, `slug` Ces trois valeurs doivent correspondre au tableau canonique. Exemple valide : ```json { "faculty_id": "faculty_grand_jeu_social", "voie_id": "voie_grand_jeu_social", "slug": "grand-jeu-social" } ``` Règles : ```text faculty_id commence par faculty_. voie_id commence par voie_. slug est en minuscules. slug n’a pas d’accents. slug utilise des tirets. slug ne doit jamais être interprété comme un chemin de fichier. ``` Règle spéciale : le slug `ia-gouvernable` peut être conservé pour compatibilité technique même si le nom public devient `Production IA` ou `Voie de la Production augmentée par l’IA`. --- # 10. `status` Valeurs autorisées : ```text draft published archived ``` Usage : ```text draft = profil en rédaction, visible seulement aux éditeurs autorisés. published = profil public si visibility=public. archived = profil retiré de la liste active. ``` Exemple : ```json "status": "published" ``` --- # 11. `visibility` Valeurs autorisées : ```text public hidden restricted ``` Usage : ```text public = accessible sans login. hidden = non accessible publiquement. restricted = accès contrôlé par capability Moodle. ``` Règle : ```text status=published avec visibility=hidden ne doit pas être listé publiquement. status=draft ne doit pas être visible anonymement. visibility=restricted doit passer par Moodle et ne doit pas exposer de données privées. ``` --- # 12. `source_atlas` Structure obligatoire : ```json { "file": "voie_grand_jeu_social.json", "schema_version_expected": "UCKK-ATLAS-0.2-draft", "sync_mode": "read_only" } ``` Valeurs autorisées pour `sync_mode` : ```text read_only preview_only moodle_sync_allowed ``` Usage recommandé : ```text read_only = défaut pour pages publiques. preview_only = prévisualisation ou brouillon. moodle_sync_allowed = autorise l’usage dans dry-run/apply admin. ``` Règle : ```text source_atlas.file doit être un nom de fichier Atlas canonique, pas un chemin. Ce champ est technique; ne pas reprendre son vocabulaire dans le texte public. ``` --- # 13. `moodle` Structure obligatoire : ```json { "category_id": null, "category_idnumber": "UCKK-GJS", "course_prefix": "GJS", "public_course_listing": true, "enrolment_visibility": "public_info_only", "hub_course_idnumber": "GJS-HUB" } ``` Valeurs autorisées pour `enrolment_visibility` : ```text hidden public_info_only login_required enrolment_required ``` Règles : ```text category_id peut rester null. category_idnumber doit correspondre au tableau canonique. course_prefix doit correspondre au code. hub_course_idnumber suit la convention CODE-HUB. public_course_listing contrôle l’affichage public du programme. ``` Exemples de hubs : ```text GJS-HUB EC-HUB ECL-HUB SP-HUB LI-HUB ME-HUB IA-HUB IS-HUB AS-HUB KOA-HUB ``` Règle éditoriale : ```text Ne pas écrire publiquement “préfixe GJS”, “préfixe ECL”, “espaces Moodle associés au préfixe”, ou “dérivé de Moodle”. Écrire plutôt “cours publics”, “accéder aux cours”, “espaces de cours disponibles”. ``` --- # 14. `identity` Structure obligatoire : ```json { "eyebrow": "Voie UCKK", "name": "", "short_name": "", "title_symbolique": "", "domain": "", "level": "Puissance opératoire", "faculty_role": "", "one_sentence": "" } ``` Règles : ```text identity.name est le nom public complet. identity.short_name est utilisé dans la navigation. identity.title_symbolique doit correspondre au JSON Atlas sauf override documenté. identity.domain doit correspondre à domaine_operatoire sauf override documenté. identity.level doit correspondre à niveau_vise. identity.one_sentence doit être public, sobre, non promotionnel. ``` Pour la Voie IA, utiliser publiquement : ```json { "name": "Voie de la Production augmentée par l’IA", "short_name": "Production IA", "title_symbolique": "Maître d’œuvre augmenté", "domain": "Production outillée" } ``` Interdit : ```text revendiquer une accréditation publique; présenter la faculté comme université reconnue par l’État; promettre un titre professionnel réglementé; présenter une reconnaissance interne comme diplôme public; présenter l’IA comme autorité finale ou instance de contrôle. ``` --- # 15. `seo` Structure obligatoire : ```json { "title": "", "description": "", "keywords": [] } ``` Bon exemple : ```json { "title": "Voie du Grand Jeu social — UCKK", "description": "Présentation publique de la Voie du Grand Jeu social dans l’Univers-Cité King Klown : repères, cours, méthodes et pratiques pour comprendre le Grand Jeu social.", "keywords": [ "UCKK", "Voie", "Grand Jeu social", "bibliothèque publique" ] } ``` Bon exemple pour la Voie IA : ```json { "title": "Production augmentée par l’IA — UCKK", "description": "La Voie de la Production augmentée par l’IA ouvre un parcours public pour utiliser l’intelligence artificielle comme outil d’écriture, de code, de graphisme, de documentation, de prototypage, d’accompagnement, de vérification et de production responsable.", "keywords": [ "UCKK", "Production IA", "Production augmentée", "intelligence artificielle", "IA comme outil", "code", "documentation", "graphisme", "écriture", "responsabilité humaine" ] } ``` Interdit comme thème SEO : ```text université accréditée; diplôme reconnu; grade universitaire officiel; certification professionnelle garantie; équivalence gouvernementale; IA autonome; IA dirigeante; contrôle par l’IA. ``` --- # 16. `hero` Structure obligatoire : ```json { "title": "", "subtitle": "", "summary": "", "primary_cta": { "label": "", "target": "" }, "secondary_cta": { "label": "", "target": "" } } ``` Targets autorisés : ```text #anchor /local/uckk/... https://... ``` Targets interdits : ```text javascript: data: file: ftp: ``` Exemple recommandé : ```json { "primary_cta": { "label": "Comprendre la voie", "target": "#programme" }, "secondary_cta": { "label": "Accéder aux cours", "target": "#cours-moodle" } } ``` Exemple recommandé pour la Voie IA : ```json { "title": "Production augmentée par l’IA", "subtitle": "Écrire, coder, créer, documenter et produire avec l’IA, sans lui déléguer l’autorité.", "summary": "Cette voie apprend à utiliser l’IA comme outil de production : livres, graphisme, programmes, documentation institutionnelle, prototypes, méthodes d’accompagnement et systèmes de travail. L’IA accélère la construction; la décision, la responsabilité et la vérification demeurent humaines.", "primary_cta": { "label": "Comprendre la voie", "target": "#programme" }, "secondary_cta": { "label": "Accéder aux cours", "target": "#cours-moodle" } } ``` --- # 17. `navigation` Structure : ```json [ { "label": "Présentation", "target": "#presentation" } ] ``` Règles : ```text Chaque target doit pointer vers un élément rendu. Chaque #target doit correspondre à un id de section, bloc dynamique, FAQ ou contact. Ne pas créer de target orpheline. Ne pas créer une section importante sans entrée de navigation. ``` Navigation recommandée : ```json [ { "label": "Présentation", "target": "#presentation" }, { "label": "Parcours", "target": "#programme" }, { "label": "Cours", "target": "#cours-moodle" }, { "label": "Projet final", "target": "#projet-final" }, { "label": "Éthique", "target": "#ethique" }, { "label": "Annonces", "target": "#annonces" } ] ``` --- # 18. `sections` Structure : ```json [ { "id": "presentation", "type": "text", "title": "", "body": "" } ] ``` Types autorisés : ```text text markdown quote principle notice cards callout two_column ``` Usage : ```text text = texte brut filtré. markdown = Markdown filtré côté serveur. quote = citation éditoriale. principle = principe institutionnel. notice = avertissement. cards = cartes éditoriales. callout = bloc accentué. two_column = layout éditorial. ``` Exemple recommandé : ```json [ { "id": "presentation", "type": "text", "title": "Présentation", "body": "Cette faculté présente une Voie comme parcours public de lecture, de méthode et de pratique dans la bibliothèque UCKK." }, { "id": "programme", "type": "text", "title": "Parcours de la Voie", "body": "Cette voie organise un parcours public pour comprendre un domaine du Grand Jeu social, reconnaître ses règles visibles et invisibles, puis développer des capacités d’action plus lucides et responsables." }, { "id": "cours", "type": "callout", "title": "Explorer les cours publics", "body": "Les cours publics sont les principales portes d’entrée dans cette voie. Ils permettent de découvrir les concepts, méthodes, exercices et artefacts d’apprentissage, puis d’ouvrir l’espace de cours correspondant lorsqu’il est disponible." } ] ``` Exemple recommandé pour la Voie IA : ```json [ { "id": "presentation", "type": "text", "title": "Une voie pour produire avec l’IA", "body": "La Voie de la Production augmentée par l’IA aborde l’intelligence artificielle comme un atelier de production. Elle sert à écrire, coder, concevoir, documenter, créer, prototyper, réviser et accompagner, sans remplacer le jugement humain." }, { "id": "programme", "type": "text", "title": "Un parcours de production outillée", "body": "Cette voie apprend à formuler une intention, préparer un contexte, dialoguer avec un modèle, transformer une sortie en matériau de travail, vérifier les résultats, documenter les limites et intégrer l’IA dans un processus productif responsable." }, { "id": "cours", "type": "callout", "title": "Explorer les cours publics", "body": "Les cours publics apprennent à utiliser l’IA pour écrire, coder, concevoir des images, préparer des documents institutionnels, prototyper des outils, soutenir l’accompagnement humain et vérifier les productions." } ] ``` Règles : ```text section.id est unique dans le fichier. section.id est en minuscules, sans espace. section.type doit être autorisé. section.body ne contient pas de HTML dangereux. section.body ne contient pas de données privées. section.body ne doit pas exposer la mécanique de sync Atlas/Moodle. ``` --- # 19. `atlas_projection` Structure complète recommandée : ```json { "show_definition_courte": true, "show_angle_fondamental": true, "show_competence_centrale": true, "show_seuils_progression": true, "show_courses": true, "show_course_codes": true, "show_concept_maitre": true, "show_concepts_associes": false, "show_artefacts": true, "show_criteres_passage": false, "show_projet_final": true, "show_limites_ethiques": true, "show_relations_intervoies": true, "show_tags": false } ``` Valeurs publiques recommandées : ```text show_courses = true show_course_codes = true show_concept_maitre = true show_concepts_associes = false show_criteres_passage = false show_projet_final = true show_limites_ethiques = true ``` Règle : ```text atlas_projection décide quoi afficher depuis Atlas. atlas_projection ne recopie pas les données Atlas. Le texte public ne doit pas parler au visiteur de projection Atlas comme si c’était le sujet de la page. ``` --- # 20. `dynamic_blocks` Structure : ```json [ { "id": "annonces", "type": "announcements", "title": "Annonces de la voie", "source": { "provider": "moodle_forum", "course_idnumber": "GJS-HUB", "forum_name": "Annonces" }, "limit": 5, "visibility": "public", "empty_state": "Aucune annonce publique pour le moment." } ] ``` Types autorisés : ```text announcements events moodle_course_list featured_courses faculty_news related_faculties public_resources cta_panel ``` Providers autorisés : ```text moodle_forum moodle_calendar moodle_category moodle_course_customfield local_uckk_news local_uckk_manual none ``` Règles : ```text dynamic_blocks affiche seulement des données publiques. Un provider inconnu invalide le profil. Un bloc dynamique doit avoir un empty_state public. Un bloc ne doit pas exposer de notes, progression, achèvement privé ou données personnelles. Le titre public d’un bloc ne doit pas être un message d’administration système. ``` --- # 21. Exemples de blocs dynamiques ## 21.1 Annonces Moodle ```json { "id": "annonces", "type": "announcements", "title": "Annonces de la voie", "source": { "provider": "moodle_forum", "course_idnumber": "GJS-HUB", "forum_name": "Annonces" }, "limit": 5, "visibility": "public", "empty_state": "Aucune annonce publique pour le moment." } ``` ## 21.2 Événements Moodle ```json { "id": "evenements", "type": "events", "title": "Événements publics", "source": { "provider": "moodle_calendar", "category_idnumber": "UCKK-GJS" }, "limit": 5, "visibility": "public", "empty_state": "Aucun événement public annoncé pour le moment." } ``` ## 21.3 Liste de cours depuis catégorie Moodle ```json { "id": "cours-moodle", "type": "moodle_course_list", "title": "Accéder aux cours", "source": { "provider": "moodle_category", "category_idnumber": "UCKK-GJS" }, "limit": 10, "visibility": "public", "empty_state": "Les cours publics de cette voie seront affichés ici lorsqu’ils seront disponibles." } ``` Éviter : ```json { "title": "Espaces Moodle associés", "empty_state": "Aucun cours Moodle public associé à cette voie pour le moment." } ``` Préférer : ```json { "title": "Accéder aux cours", "empty_state": "Les cours publics de cette voie seront affichés ici lorsqu’ils seront disponibles." } ``` ## 21.4 Bloc manuel ```json { "id": "ressources", "type": "public_resources", "title": "Ressources publiques", "source": { "provider": "local_uckk_manual", "items": [ { "label": "Guide public de la faculté", "url": "/local/uckk/faculty.php?slug=grand-jeu-social" } ] }, "limit": 3, "visibility": "public", "empty_state": "Aucune ressource publique pour le moment." } ``` ## 21.5 Bloc désactivé sans provider ```json { "id": "appel", "type": "cta_panel", "title": "Participer", "source": { "provider": "none" }, "limit": 1, "visibility": "public", "empty_state": "Les modalités de participation seront annoncées plus tard." } ``` --- # 22. `featured_blocks` Structure : ```json [ { "type": "principle", "title": "", "body": "" } ] ``` Types autorisés par le validateur : ```text principle notice warning quote stat method ethics cta ``` Usage recommandé : ```text Les featured_blocks servent à mettre en avant les principes publics de la Voie : lecture du monde, méthode, accès au savoir, éthique, pratique, orientation. Ils ne doivent pas devenir un espace de répétition des limites d’accréditation. ``` Exemple recommandé : ```json [ { "type": "principle", "title": "Voir le jeu avant de jouer", "body": "Toute action responsable commence par la lecture des règles, des positions, des ressources, des récits et des preuves qui structurent une situation." }, { "type": "method", "title": "Ouvrir l’accès au savoir", "body": "Cette Voie fait partie d’une bibliothèque publique vivante : elle sert à rendre les outils de compréhension plus accessibles, plus partageables et plus praticables." }, { "type": "ethics", "title": "Agir avec responsabilité", "body": "La puissance opératoire visée doit rester lisible, contestable, responsable et compatible avec l’intégrité des personnes concernées." } ] ``` Exemple recommandé pour la Voie IA : ```json [ { "type": "principle", "title": "L’IA comme outil de production", "body": "L’IA sert à écrire, coder, créer, documenter, prototyper, comparer, corriger et accélérer le travail humain. Elle ne reçoit pas l’autorité finale." }, { "type": "method", "title": "Transformer la sortie en matériau", "body": "Une réponse d’IA n’est qu’un point de départ. La méthode consiste à la relire, la tester, la corriger, la situer, la comparer et l’intégrer dans un travail humain vérifiable." }, { "type": "ethics", "title": "Ne pas déléguer l’autorité", "body": "kOA n’utilise pas l’IA pour remplacer le jugement humain. L’IA peut accélérer la production, mais la responsabilité, la décision et l’interprétation demeurent humaines." } ] ``` À éviter dans `featured_blocks` : ```text un bloc principal intitulé Reconnaissance interne; une répétition de la formule diplôme/accréditation; une mise en scène défensive de ce que la Voie n’est pas; un type non validé comme library ou knowledge si le validateur ne l’autorise pas. ``` --- # 23. `faq` Structure : ```json [ { "question": "", "answer": "" } ] ``` Règles : ```text FAQ publique seulement. Ne pas répondre sur progression individuelle. Ne pas promettre accréditation. Ne pas fournir de conseil légal, médical ou financier comme autorité UCKK. Ne pas présenter le Parchemin comme diplôme public. Ne pas transformer la FAQ en répétition des limites institutionnelles. ``` Exemples recommandés : ```json [ { "question": "Par où commencer?", "answer": "Commencez par la présentation de la voie, puis ouvrez les cours publics disponibles. Chaque cours sert de porte d’entrée vers une notion, une méthode ou un artefact d’apprentissage." }, { "question": "Faut-il être inscrit pour apprendre?", "answer": "Les pages publiques donnent accès aux repères essentiels de la voie. Certains espaces de cours peuvent demander une connexion ou une inscription selon leur usage, mais l’orientation générale du savoir reste publique." }, { "question": "Que signifie le titre symbolique associé à cette Voie?", "answer": "C’est un repère narratif et pédagogique interne. Il aide à nommer une posture d’apprentissage ou de pratique. Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future." } ] ``` Exemples recommandés pour la Voie IA : ```json [ { "question": "Cette voie apprend-elle à donner le contrôle à l’IA?", "answer": "Non. Cette voie apprend à utiliser l’IA comme outil de production. Elle aide à écrire, coder, créer, documenter, prototyper, accompagner et vérifier, sans déplacer l’autorité finale hors du jugement humain." }, { "question": "Que peut-on produire avec l’IA?", "answer": "On peut produire des livres, images, interfaces, scripts, programmes, documents institutionnels, assistants, cartes, analyses, protocoles, méthodes d’accompagnement et systèmes de travail. Chaque production doit être relue, testée, corrigée et assumée humainement." }, { "question": "Que signifie Maître d’œuvre augmenté?", "answer": "C’est le titre symbolique associé à cette voie. Il désigne une posture de production responsable : coordonner des outils d’IA, garder l’intention humaine, vérifier les résultats et assumer les choix. Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future." } ] ``` La mention de reconnaissance doit apparaître au plus une fois par page publique : ```text Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future. ``` Ne pas ajouter systématiquement : ```text Il n’y a pas de projet à court terme d’offrir des certifications, diplômes ou titres formels. ``` Cette information peut être vraie, mais elle ne doit pas devenir un thème répété. --- # 24. `contact` Structure : ```json { "label": "Contact", "body": "", "email": "", "cta": { "label": "", "target": "" } } ``` Règles : ```text email peut être vide. email ne doit pas être une adresse privée sans consentement. cta.target peut pointer vers #annonces, #contact ou une page local_uckk autorisée. Le texte de contact doit orienter l’utilisateur, pas décrire la mécanique Moodle. ``` Exemple recommandé : ```json { "label": "Contact", "body": "Pour suivre cette voie, commencez par les cours disponibles, puis consultez les annonces publiques pour les nouvelles, rencontres et ouvertures d’espaces d’apprentissage.", "email": "", "cta": { "label": "Voir les annonces", "target": "#annonces" } } ``` --- # 25. `governance` Structure obligatoire : ```json { "owner": "local_uckk", "editorial_status": "draft", "last_reviewed": null, "review_notes": "", "public_claims_guardrails": [] } ``` Valeurs autorisées pour `editorial_status` : ```text draft review approved needs_update archived ``` Guardrail recommandé : ```json [ "Garder la note de reconnaissance unique, discrète et non centrale; ne pas transformer la page publique en avertissement répété sur les diplômes, statuts ou certifications." ] ``` Guardrail recommandé pour la Voie IA : ```json [ "Présenter l’IA comme outil de production, jamais comme autorité finale, sujet de gouvernance autonome ou instance de contrôle." ] ``` Règles : ```text public_claims_guardrails peut être vide si la page ne présente pas de risque public particulier. S’il est présent, il ne doit pas contenir une longue liste répétitive. Les guardrails sont des notes de gouvernance éditoriale, pas le message principal de la page. La limite institutionnelle sur les reconnaissances doit rester vraie, mais ne doit pas dominer le contenu public. ``` --- # 26. `cache` Structure obligatoire : ```json { "enabled": true, "ttl_seconds": 3600 } ``` Règles : ```text enabled=true par défaut. ttl_seconds=3600 par défaut. ttl_seconds doit être un entier positif. Une page publique doit pouvoir être purgée par local_uckk. ``` --- # 27. Règles de rédaction publique Chaque profil doit respecter ces règles : ```text Ton public, sobre, institutionnel. Priorité à la diffusion du savoir. Priorité à la bibliothèque publique vivante. Priorité à la lisibilité, à la méthode et à la pratique. Priorité aux cours publics comme portes d’entrée. Aucune promesse d’accréditation. Aucune promesse de reconnaissance gouvernementale. Aucune promesse professionnelle réglementée. Aucune donnée privée Moodle. Aucune note, achèvement, progression, inscription individuelle. Aucune confusion entre Voie, cours Moodle, catégorie Moodle et faculté publique. ``` Formules autorisées : ```text Page de faculté UCKK. Voie UCKK. Parcours public de lecture, de méthode et de pratique. Bibliothèque publique vivante. Cadre d’apprentissage ouvert. Diffusion publique du savoir. Cours publics. Accéder aux cours. Explorer les cours publics. Reconnaissance interne UCKK, sauf reconnaissance officielle future. ``` Formules à éviter comme thèmes principaux : ```text diplôme public accrédité; université officiellement reconnue; grade universitaire d’État; certification professionnelle garantie; équivalence officielle; titre légalement reconnu; cette Voie ne donne pas de diplôme; non accrédité; aucun statut universitaire public; préfixe Moodle; dérivé de l’Atlas; projeté depuis le JSON Atlas; espaces Moodle associés. ``` Pour la Voie IA, éviter : ```text Production IA comme nom public principal; donner le contrôle à l’IA; gouvernance autonome de l’IA; IA comme décideur; IA comme autorité finale. ``` Pour la Voie IA, préférer : ```text Production augmentée par l’IA; Production IA; Maître d’œuvre augmenté; IA comme outil de production; écrire, coder, créer, documenter, accompagner, prototyper, vérifier; responsabilité humaine; production vérifiable. ``` --- # 28. Règles de sécurité éditoriale Ne jamais afficher publiquement : ```text notes; progression individuelle; achèvement individuel; statut d’inscription individuel; feedback privé; soumissions privées; preuves privées; votes privés; données personnelles; adresses privées; cas d’intégrité; journaux IA privés; rapports confidentiels; commentaires internes. ``` Si un bloc dynamique provient de Moodle, il doit filtrer avant rendu. --- # 29. Contrôle des anchors Chaque navigation target doit correspondre à un élément rendu. Valide : ```json { "label": "Cours", "target": "#cours-moodle" } ``` si `dynamic_blocks` contient : ```json { "id": "cours-moodle", "type": "moodle_course_list" } ``` Invalide : ```json { "label": "Ressources", "target": "#ressources" } ``` si aucune section ou bloc dynamique n’a : ```json "id": "ressources" ``` Anchors recommandés : ```text #presentation #programme #cours #cours-moodle #projet-final #ethique #annonces #evenements #faq #contact ``` --- # 30. Contrôle des providers Providers autorisés : ```text moodle_forum moodle_calendar moodle_category moodle_course_customfield local_uckk_news local_uckk_manual none ``` Interdit : ```json { "provider": "wordpress" } ``` ```json { "provider": "google_calendar" } ``` ```json { "provider": "custom_api" } ``` Si un nouveau provider est nécessaire, il doit être ajouté dans : ```text docs/12_faculty_pages_atlas_public_contract.md docs/13_faculty_json_authoring_guide.md local/uckk/classes/local/faculty/faculty_validator.php local/uckk/classes/local/faculty/faculty_dynamic_block_provider.php ``` --- # 31. Contrôle des IDs Les IDs suivants ne doivent jamais être renommés sans migration explicite : ```text faculty_id voie_id slug category_idnumber course_prefix hub_course_idnumber source_atlas.file ``` Règle : ```text Changer le nom public est permis. Changer l’ID technique exige une migration. ``` Exemple : ```text Nom public de la Voie IA = Voie de la Production augmentée par l’IA ID technique conservé = voie_ia_gouvernable Slug conservé = ia-gouvernable ``` --- # 32. Exemple abrégé pour `economie.faculty.json` ```json { "schema_version": "UCKK-FACULTY-0.1", "faculty_id": "faculty_economie", "voie_id": "voie_economie", "slug": "economie", "status": "published", "visibility": "public", "source_atlas": { "file": "voie_economie.json", "schema_version_expected": "UCKK-ATLAS-0.2-draft", "sync_mode": "read_only" }, "moodle": { "category_id": null, "category_idnumber": "UCKK-EC", "course_prefix": "EC", "public_course_listing": true, "enrolment_visibility": "public_info_only", "hub_course_idnumber": "EC-HUB" }, "identity": { "eyebrow": "Voie fondatrice UCKK", "name": "Voie d’Économie", "short_name": "Économie", "title_symbolique": "Architecte d’opportunités", "domain": "Ressources", "level": "Puissance opératoire", "faculty_role": "Voie qui apprend à lire, cartographier et transformer les règles de circulation, de capture et de redistribution de la valeur.", "one_sentence": "Comprendre les ressources, les flux, les incitatifs, les marchés, le travail, la valeur et les modèles économiques comme règles du Grand Jeu social." }, "seo": { "title": "Voie d’Économie — UCKK", "description": "Présentation publique de la Voie d’Économie : ressources, flux, valeur, marchés, travail, capture, redistribution et modèles économiques dans le Grand Jeu social.", "keywords": [ "UCKK", "Économie", "ressources", "valeur", "marchés", "travail", "Grand Jeu social" ] }, "hero": { "title": "Voie d’Économie", "subtitle": "Lire les ressources, les flux, la valeur et les opportunités.", "summary": "Cette voie ouvre un parcours public pour comprendre les règles économiques du Grand Jeu social : production, échange, capture, redistribution, travail, incitatifs, modèles d’affaires et conditions d’accès aux ressources.", "primary_cta": { "label": "Comprendre la voie", "target": "#programme" }, "secondary_cta": { "label": "Accéder aux cours", "target": "#cours-moodle" } }, "sections": [ { "id": "presentation", "type": "text", "title": "Une voie pour lire les règles de la valeur", "body": "La Voie d’Économie étudie les ressources, les flux, les incitatifs, les marchés, le travail, la dette, la valeur, la capture et la redistribution comme règles du Grand Jeu social." }, { "id": "programme", "type": "text", "title": "Parcours de la Voie", "body": "Cette voie organise un parcours public pour comprendre comment la valeur circule, où elle se concentre, comment elle se justifie et quelles formes de redistribution ou de transformation deviennent possibles." }, { "id": "cours", "type": "callout", "title": "Explorer les cours publics", "body": "Les cours publics sont les principales portes d’entrée dans cette voie. Ils permettent de découvrir les concepts, méthodes, exercices et artefacts d’apprentissage, puis d’ouvrir l’espace de cours correspondant lorsqu’il est disponible." } ], "dynamic_blocks": [ { "id": "cours-moodle", "type": "moodle_course_list", "title": "Accéder aux cours", "source": { "provider": "moodle_category", "category_idnumber": "UCKK-EC" }, "limit": 10, "visibility": "public", "empty_state": "Les cours publics de cette voie seront affichés ici lorsqu’ils seront disponibles." } ], "governance": { "owner": "local_uckk", "editorial_status": "approved", "last_reviewed": null, "review_notes": "", "public_claims_guardrails": [ "Garder la note de reconnaissance unique, discrète et non centrale; ne pas transformer la page publique en avertissement répété sur les diplômes, statuts ou certifications." ] }, "cache": { "enabled": true, "ttl_seconds": 3600 } } ``` --- # 33. Exemple abrégé pour `ia-gouvernable.faculty.json` ```json { "schema_version": "UCKK-FACULTY-0.1", "faculty_id": "faculty_ia_gouvernable", "voie_id": "voie_ia_gouvernable", "slug": "ia-gouvernable", "status": "published", "visibility": "public", "source_atlas": { "file": "voie_ia_gouvernable.json", "schema_version_expected": "UCKK-ATLAS-0.2-draft", "sync_mode": "read_only" }, "moodle": { "category_id": null, "category_idnumber": "UCKK-IA", "course_prefix": "IA", "public_course_listing": true, "enrolment_visibility": "public_info_only", "hub_course_idnumber": "IA-HUB" }, "identity": { "eyebrow": "Voie ouverte UCKK", "name": "Voie de la Production augmentée par l’IA", "short_name": "Production IA", "title_symbolique": "Maître d’œuvre augmenté", "domain": "Production outillée", "level": "Puissance opératoire", "faculty_role": "Voie consacrée à l’usage de l’intelligence artificielle comme outil de production, d’écriture, de code, de graphisme, de documentation, d’accompagnement, de prototypage, de vérification et d’accélération du travail humain.", "one_sentence": "Utiliser l’IA pour produire mieux, documenter plus clairement, vérifier davantage et relier les idées, sans lui déléguer la décision, la responsabilité ou l’autorité finale." }, "hero": { "title": "Production augmentée par l’IA", "subtitle": "Écrire, coder, créer, documenter et produire avec l’IA, sans lui déléguer l’autorité.", "summary": "Cette voie apprend à utiliser l’IA comme outil de production : livres, graphisme, programmes, documentation institutionnelle, prototypes, méthodes d’accompagnement et systèmes de travail. L’IA accélère la construction; la décision, la responsabilité et la vérification demeurent humaines.", "primary_cta": { "label": "Comprendre la voie", "target": "#programme" }, "secondary_cta": { "label": "Accéder aux cours", "target": "#cours-moodle" } }, "governance": { "owner": "local_uckk", "editorial_status": "approved", "last_reviewed": null, "review_notes": "Note éditoriale interne : renommage public vers Production augmentée par l’IA. Les identifiants techniques faculty_ia_gouvernable, voie_ia_gouvernable et ia-gouvernable sont conservés pour compatibilité Atlas/Moodle.", "public_claims_guardrails": [ "Présenter l’IA comme outil de production, jamais comme autorité finale, sujet de gouvernance autonome ou instance de contrôle." ] } } ``` --- # 34. Validation manuelle avant commit Avant commit, vérifier : ```text [ ] Le JSON est syntaxiquement valide. [ ] Le schema_version est UCKK-FACULTY-0.1. [ ] faculty_id correspond au manifest. [ ] voie_id correspond au manifest. [ ] slug correspond au manifest. [ ] source_atlas.file existe. [ ] category_idnumber correspond au manifest. [ ] course_prefix correspond au code. [ ] Tous les CTA pointent vers des anchors existants. [ ] Tous les providers sont autorisés. [ ] Tous les featured_blocks.type sont autorisés. [ ] Aucun contenu privé Moodle n’est exposé. [ ] Le texte public ne contient pas de jargon de sync Atlas/Moodle. [ ] La note de reconnaissance n’apparaît pas plus d’une fois. [ ] Les cours sont présentés comme portes d’entrée publiques. [ ] Pour la Voie IA, le nom public est Production augmentée par l’IA. [ ] Pour la Voie IA, le titre symbolique est Maître d’œuvre augmenté. [ ] Pour la Voie IA, l’IA est présentée comme outil de production, jamais comme autorité. ``` --- # 35. Validation CLI recommandée Commandes recommandées : ```bash php -l local/uckk/classes/local/faculty/faculty_validator.php php -l local/uckk/classes/local/faculty/faculty_page_builder.php ``` Validation JSON : ```bash python -m json.tool local/uckk/content/faculties/grand-jeu-social.faculty.json >/dev/null python -m json.tool local/uckk/content/faculties/economie.faculty.json >/dev/null python -m json.tool local/uckk/content/faculties/ecologie.faculty.json >/dev/null python -m json.tool local/uckk/content/faculties/sciences-politiques.faculty.json >/dev/null python -m json.tool local/uckk/content/faculties/linguistique-architecture-du-sens.faculty.json >/dev/null python -m json.tool local/uckk/content/faculties/metaphysique.faculty.json >/dev/null python -m json.tool local/uckk/content/faculties/ia-gouvernable.faculty.json >/dev/null python -m json.tool local/uckk/content/faculties/intervention-sociale-systemes-humains.faculty.json >/dev/null python -m json.tool local/uckk/content/faculties/architecture-sociotechnique.faculty.json >/dev/null python -m json.tool local/uckk/content/faculties/ecosysteme-digital-koa.faculty.json >/dev/null ``` Validation applicative recommandée : ```bash php admin/cli/purge_caches.php php local/uckk/cli/validate_faculties.php ``` --- # 36. Erreurs fréquentes ## 36.1 Mauvais emplacement Interdit : ```text local/uckk/grand-jeu-social.faculty.json ``` Correct : ```text local/uckk/content/faculties/grand-jeu-social.faculty.json ``` ## 36.2 Duplication des cours Atlas Interdit : ```json "courses": [] ``` Correct : ```json "atlas_projection": { "show_courses": true } ``` ## 36.3 Provider inventé Interdit : ```json "provider": "notion" ``` Correct : ```json "provider": "local_uckk_manual" ``` ou : ```json "provider": "moodle_category" ``` ## 36.4 Target orpheline Interdit : ```json { "label": "Cours", "target": "#cours" } ``` si aucun élément rendu ne porte : ```json "id": "cours" ``` Correct : ```json { "label": "Cours", "target": "#cours-moodle" } ``` si le bloc dynamique existe : ```json { "id": "cours-moodle", "type": "moodle_course_list" } ``` ## 36.5 Confusion accréditation Mauvais thème principal : ```text Cette Voie ne donne pas un diplôme public accrédité. ``` Meilleure formulation, si nécessaire une seule fois : ```text Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future. ``` ## 36.6 Messages trop système À éviter : ```text Le programme public est projeté depuis le JSON Atlas. Les cours sont dérivés de l’Atlas et des espaces Moodle visibles associés au préfixe AS. Espaces Moodle associés. Aucun cours Moodle public associé à cette voie pour le moment. ``` À écrire : ```text Cette voie organise un parcours public de lecture, de méthode et de pratique. Les cours publics sont les principales portes d’entrée dans cette voie. Accéder aux cours. Les cours publics de cette voie seront affichés ici lorsqu’ils seront disponibles. ``` ## 36.7 Mauvais cadrage de la Voie IA À éviter : ```text Voie de la Production augmentée par l’IA. Production IA. Bâtisseur augmenté. Donner le contrôle à l’IA. Gouvernance autonome des systèmes d’IA. ``` À écrire : ```text Voie de la Production augmentée par l’IA. Production IA. Maître d’œuvre augmenté. Utiliser l’IA comme outil de production. Écrire, coder, créer, documenter, accompagner, prototyper et vérifier avec l’IA. La responsabilité et l’autorité finale demeurent humaines. ``` --- # 37. Règles IA anti-drift pour l’auteur Avant de modifier un `*.faculty.json`, une IA doit identifier : ```text 1. Le fichier exact. 2. La faculté concernée. 3. Le voie_id. 4. Le faculty_id. 5. Le slug. 6. Le fichier Atlas. 7. Le code et le course_prefix. 8. Les anchors existants. 9. Les dynamic_blocks existants. 10. Les provider names existants. 11. Les types autorisés. 12. Les textes publics à corriger. 13. Les notes institutionnelles répétées. 14. Les formulations système à supprimer. ``` Une IA ne doit pas inventer : ```text nouveau voie_id; nouveau faculty_id; nouveau slug; nouveau course_prefix; nouveau provider; nouveau type de bloc; nouveau champ top-level; nouvelle variable Mustache; nouveau statut; nouvelle visibilité; nouvelle capacité Moodle. ``` Exception : un nom public peut être modifié sans changer les IDs techniques, si la compatibilité est explicitement documentée dans `review_notes`. --- # 38. Résumé opératoire ```text Un Faculty JSON n’est pas le programme complet. Un Faculty JSON est la présentation publique d’une Voie. Le visiteur doit comprendre quoi apprendre, pourquoi cela compte, et où accéder aux cours. Le texte public doit parler de savoir, méthode, pratique, cours et responsabilité. Le texte public ne doit pas parler comme un système de sync Atlas/Moodle. Les cours publics sont des portes d’entrée, pas une barrière. La reconnaissance UCKK reste interne, sauf reconnaissance officielle future, mais cette limite ne doit pas dominer la page. Les identifiants techniques restent stables. Les noms publics peuvent évoluer lorsque le canon éditorial l’exige. La Voie IA s’appelle publiquement Production augmentée par l’IA. L’IA est un outil de production, pas une autorité finale. ``` Formule finale : ```text Atlas enseigne. Faculty raconte. Moodle exécute. local_uckk relie. Mustache affiche. La page publique ouvre le savoir. Les cours donnent accès. L’IA aide à produire. L’humain demeure responsable. ``` ================================================================================================ FILE: docs/14_atlas_moodle_sync_reference.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: b64a06f3578145f341859c14d489d0731fd33cb8e8f632b41ce92327c2e73fc4 CONTENT_BYTES: 48126 ================================================================================================ # DOC_14 — UCKK Atlas → Moodle Sync Reference **Document canonique proposé :** `docs/14_atlas_moodle_sync_reference.md` **Composant principal :** `local_uckk` **Portée :** référence technique pour la validation, le mapping, le dry-run, l’application contrôlée et le reporting de synchronisation entre les JSON Atlas, les profils Faculty JSON et Moodle. **Dépendance normative :** `docs/12_faculty_pages_atlas_public_contract.md` **Dépendance auteur :** `docs/13_faculty_json_authoring_guide.md` **Statut :** référence d’implémentation. **Version :** `UCKK-ATLAS-MOODLE-SYNC-REFERENCE-0.2` **Feature canonique :** `uckk_atlas_moodle_sync` **Composant Moodle propriétaire :** `local_uckk` --- # 1. Objet Ce document définit comment `local_uckk` prépare, valide, compare et synchronise les informations publiques, pédagogiques et opérationnelles issues des JSON Atlas et Faculty vers Moodle. La synchronisation ne remplace pas les JSON. Elle produit ou met à jour uniquement des objets Moodle dérivés, contrôlés et traçables. La projection publique doit soutenir la fonction première de l’UCKK : ```text ouvrir une bibliothèque publique vivante; rendre les connaissances accessibles; organiser des parcours de lecture et d’apprentissage; relier cours, Voies, médias, archives, défis et assemblées; préserver les traces utiles sans exposer de données privées. ``` Formule canonique : ```text Atlas JSON → vérité canonique de la Voie Faculty JSON → vérité éditoriale publique de la faculté Moodle → vérité opérationnelle des catégories, cours, annonces, événements, badges, accès et espaces d’apprentissage local_uckk → lit, valide, normalise, compare, prépare, rapporte et applique les changements autorisés ``` --- # 2. Principe de non-destruction La synchronisation Atlas → Moodle doit être conservatrice. Elle doit : ```text valider avant de mapper; normaliser avant de comparer; comparer avant d’écrire; faire un dry-run avant tout apply; journaliser uniquement ids, statuts, compteurs et hashes; ne jamais exposer de données privées; ne jamais supprimer du contenu Moodle non géré par UCKK sans règle explicite; préserver la fonction publique de bibliothèque ouverte; éviter de transformer une reconnaissance interne en promesse externe. ``` Elle ne doit pas : ```text modifier les JSON Atlas; modifier les JSON Faculty; inscrire automatiquement des utilisateurs; modifier des notes; modifier des progressions individuelles; publier des badges personnels; exposer des données privées; créer des rôles symboliques; déduire des permissions depuis un titre symbolique; confondre publication publique du savoir et certification formelle. ``` --- # 3. Sources de vérité | Couche | Source | Autorité | Peut être modifiée par sync | | --------------------- | ---------------------------------------------------- | ------------------------------------- | -------------------------------------------- | | Programme pédagogique | `local/uckk/atlas/voies/voie_*.json` | Vérité canonique de la Voie | Non | | Manifest Atlas | `local/uckk/atlas/atlas_manifest.json` | Index des Voies autorisées | Non | | Page publique | `local/uckk/content/faculties/*.faculty.json` | Vérité éditoriale publique | Non | | Manifest Faculty | `local/uckk/content/faculties/faculty_manifest.json` | Index des facultés autorisées | Non | | Moodle category | Base Moodle | Vérité opérationnelle | Oui, si dry-run valide | | Moodle course | Base Moodle | Vérité opérationnelle | Oui, si dry-run valide | | Moodle custom fields | Base Moodle | Métadonnées de sync | Oui, si dry-run valide | | Moodle badge | Base Moodle | Reconnaissance interne opérationnelle | Oui, si explicitement activé | | Moodle forum/calendar | Base Moodle | Source dynamique publique | Lecture prioritaire; écriture non nécessaire | --- # 4. Fichiers impliqués ## 4.1 Fichiers JSON ```text local/uckk/atlas/atlas_manifest.json local/uckk/atlas/atlas_schema.json local/uckk/atlas/voies/voie_*.json local/uckk/content/faculties/faculty_manifest.json local/uckk/content/faculties/faculty_schema.json local/uckk/content/faculties/*.faculty.json ``` ## 4.2 Services PHP Atlas ```text local/uckk/classes/local/atlas/atlas_manifest.php local/uckk/classes/local/atlas/voie_repository.php local/uckk/classes/local/atlas/voie_validator.php local/uckk/classes/local/atlas/voie_normalizer.php local/uckk/classes/local/atlas/voie_slugger.php local/uckk/classes/local/atlas/voie_moodle_mapper.php local/uckk/classes/local/atlas/atlas_cache.php ``` ## 4.3 Services PHP Faculty ```text local/uckk/classes/local/faculty/faculty_manifest.php local/uckk/classes/local/faculty/faculty_registry.php local/uckk/classes/local/faculty/faculty_repository.php local/uckk/classes/local/faculty/faculty_validator.php local/uckk/classes/local/faculty/faculty_normalizer.php local/uckk/classes/local/faculty/faculty_page_builder.php local/uckk/classes/local/faculty/faculty_moodle_mapper.php local/uckk/classes/local/faculty/faculty_cache.php ``` ## 4.4 Contrôleurs et outils ```text local/uckk/faculty_sync.php local/uckk/faculty_validate.php local/uckk/faculty_cache.php local/uckk/cli/sync_atlas.php local/uckk/cli/validate_faculties.php local/uckk/cli/purge_faculty_cache.php ``` ## 4.5 Services externes optionnels ```text local/uckk/classes/external/validate_atlas_voie.php local/uckk/classes/external/validate_faculty_profile.php local/uckk/classes/external/get_faculty_sync_report.php local/uckk/classes/external/run_atlas_sync_dryrun.php ``` ## 4.6 DB declarations ```text local/uckk/db/access.php local/uckk/db/caches.php local/uckk/db/services.php ``` ## 4.7 Events ```text local/uckk/classes/event/atlas_voie_validated.php local/uckk/classes/event/atlas_sync_dryrun_completed.php local/uckk/classes/event/atlas_sync_applied.php local/uckk/classes/event/faculty_profile_validated.php local/uckk/classes/event/faculty_cache_purged.php ``` --- # 5. Modes de synchronisation ## 5.1 Modes autorisés ```text validate dry_run apply report ``` ## 5.2 `validate` `validate` lit les JSON, valide les manifests, valide les schémas, vérifie les correspondances et produit un rapport sans contacter les fonctions d’écriture Moodle. Actions autorisées : ```text charger atlas_manifest.json; charger faculty_manifest.json; charger les 10 JSON Atlas; charger les 10 JSON Faculty; valider les schémas; normaliser les structures; calculer les hashes sources; vérifier les IDs canoniques; vérifier les slugs; vérifier les correspondances Atlas ↔ Faculty; retourner erreurs, warnings, compteurs. ``` Actions interdites : ```text créer catégorie; créer cours; modifier cours; modifier badge; vider cache; émettre event apply. ``` ## 5.3 `dry_run` `dry_run` compare l’état normalisé attendu avec l’état réel Moodle et produit un plan. Actions autorisées : ```text tout ce que validate autorise; chercher catégories Moodle existantes; chercher cours Moodle existants; chercher custom fields existants; calculer create/update/unchanged/warning/blocker; produire un sync report; émettre atlas_sync_dryrun_completed. ``` Actions interdites : ```text écrire dans Moodle; créer catégorie; créer cours; modifier cours; modifier badge; supprimer objet Moodle; modifier cohort; modifier rôle; modifier inscription. ``` ## 5.4 `apply` `apply` applique uniquement un plan qui a passé `dry_run`. Actions autorisées : ```text créer ou mettre à jour catégories Moodle autorisées; créer ou mettre à jour cours Moodle autorisés; écrire les custom fields autorisés; créer ou mettre à jour badges de Voie si explicitement activé; écrire les hashes de source; écrire le sync status; purger caches concernés; émettre atlas_sync_applied. ``` Actions interdites : ```text appliquer sans validation; appliquer sans capability; modifier notes; modifier progressions individuelles; inscrire des utilisateurs; supprimer contenu non UCKK; modifier activités apprenantes existantes non gérées; écrire des données privées dans les logs. ``` ## 5.5 `report` `report` lit le dernier rapport disponible ou reconstruit un rapport de comparaison sans appliquer. Actions autorisées : ```text résumer état Atlas; résumer état Faculty; résumer état Moodle; afficher actions recommandées; afficher warnings et blockers; afficher source hashes; afficher last sync status. ``` --- # 6. Capabilities | Variable | Capability | Usage | | ------------------------------ | ---------------------------------- | --------------------------------- | | `CAP_VALIDATE_ATLAS_JSON` | `local/uckk:validateatlasjson` | Lancer validation Atlas | | `CAP_MANAGE_FACULTY_PROFILES` | `local/uckk:managefacultyprofiles` | Valider ou gérer profils Faculty | | `CAP_SYNC_ATLAS_MOODLE` | `local/uckk:syncatlasmoodle` | Lancer dry-run ou apply | | `CAP_VIEW_FACULTY_SYNC_REPORT` | `local/uckk:viewfacultysyncreport` | Voir rapports de sync | | `CAP_PURGE_FACULTY_CACHE` | `local/uckk:purgefacultycache` | Purger cache des pages de faculté | Règles : ```text validate côté admin exige capability. dry_run exige CAP_SYNC_ATLAS_MOODLE. apply exige CAP_SYNC_ATLAS_MOODLE. report exige CAP_VIEW_FACULTY_SYNC_REPORT. Les visiteurs anonymes ne peuvent jamais lancer sync. Aucun titre symbolique ne donne permission. Aucune faculté ne donne permission par elle-même. ``` --- # 7. Ordre d’exécution canonique ```text 1. Charger atlas_manifest.json. 2. Charger faculty_manifest.json. 3. Valider les manifests. 4. Pour chaque item canonique : 4.1 charger le JSON Atlas; 4.2 valider le JSON Atlas; 4.3 normaliser le JSON Atlas; 4.4 charger le JSON Faculty; 4.5 valider le JSON Faculty; 4.6 normaliser le JSON Faculty; 4.7 vérifier la correspondance Atlas ↔ Faculty; 4.8 mapper vers un modèle Moodle attendu; 4.9 lire l’état Moodle réel; 4.10 calculer le diff; 4.11 produire actions prévues. 5. Si mode=dry_run, retourner le plan sans écrire. 6. Si mode=apply, appliquer seulement les actions autorisées. 7. Émettre l’event correspondant. 8. Purger les caches concernés si apply modifie des données publiques. 9. Retourner un rapport complet. ``` --- # 8. Correspondance canonique des 10 facultés | Ordre | `voie_id` | `faculty_id` | `slug` | Nom public recommandé | Nom court public | `code` | `course_prefix` | `category_idnumber` | Hub | | ----: | -------------------------------------------- | ----------------------------------------------- | --------------------------------------- | ---------------------------------------------- | ----------------------- | ------ | --------------- | ------------------- | --------- | | 1 | `voie_grand_jeu_social` | `faculty_grand_jeu_social` | `grand-jeu-social` | Voie du Grand Jeu social | Grand Jeu social | `GJS` | `GJS` | `UCKK-GJS` | `GJS-HUB` | | 2 | `voie_economie` | `faculty_economie` | `economie` | Voie d’Économie | Économie | `EC` | `EC` | `UCKK-EC` | `EC-HUB` | | 3 | `voie_ecologie` | `faculty_ecologie` | `ecologie` | Voie d’Écologie | Écologie | `ECL` | `ECL` | `UCKK-ECL` | `ECL-HUB` | | 4 | `voie_sciences_politiques` | `faculty_sciences_politiques` | `sciences-politiques` | Voie des Sciences politiques | Sciences politiques | `SP` | `SP` | `UCKK-SP` | `SP-HUB` | | 5 | `voie_linguistique_architecture_du_sens` | `faculty_linguistique_architecture_du_sens` | `linguistique-architecture-du-sens` | Voie de la Linguistique et de l’architecture du sens | Linguistique et sens | `LI` | `LI` | `UCKK-LI` | `LI-HUB` | | 6 | `voie_metaphysique` | `faculty_metaphysique` | `metaphysique` | Voie de la Métaphysique | Métaphysique | `ME` | `ME` | `UCKK-ME` | `ME-HUB` | | 7 | `voie_ia_gouvernable` | `faculty_ia_gouvernable` | `ia-gouvernable` | Voie de la Production augmentée par l’IA | Production IA | `IA` | `IA` | `UCKK-IA` | `IA-HUB` | | 8 | `voie_intervention_sociale_systemes_humains` | `faculty_intervention_sociale_systemes_humains` | `intervention-sociale-systemes-humains` | Voie de l’Intervention sociale et des systèmes humains | Intervention sociale | `IS` | `IS` | `UCKK-IS` | `IS-HUB` | | 9 | `voie_architecture_sociotechnique` | `faculty_architecture_sociotechnique` | `architecture-sociotechnique` | Voie d’Architecture sociotechnique | Architecture sociotechnique | `AS` | `AS` | `UCKK-AS` | `AS-HUB` | | 10 | `voie_ecosysteme_digital_koa` | `faculty_ecosysteme_digital_koa` | `ecosysteme-digital-koa` | Voie de l’Architecture de l’écosystème digital kOA | Écosystème digital kOA | `KOA` | `KOA` | `UCKK-KOA` | `KOA-HUB` | ## 8.1 Règle de compatibilité pour la voie IA Les identifiants techniques historiques de la voie IA restent stables afin de ne pas casser les manifests, le mapping Moodle, les catégories, les cours, les badges et les rapports de sync. ```text voie_id = voie_ia_gouvernable faculty_id = faculty_ia_gouvernable slug = ia-gouvernable code = IA course_prefix = IA category_idnumber = UCKK-IA hub_course_idnumber = IA-HUB atlas_file = voie_ia_gouvernable.json faculty_file = ia-gouvernable.faculty.json ``` Le nom public et éditorial de cette voie n’est plus « IA gouvernable ». Utiliser : ```text Nom public = Voie de la Production augmentée par l’IA Nom court principal = Production IA Nom court éditorial = Production augmentée Titre symbolique = Maître d’œuvre augmenté Domaine public = Production outillée ``` Règle éditoriale : l’IA est présentée comme un outil de production, de création, de recherche, d’écriture, de graphisme, de programmation, de documentation, d’accompagnement, de prototypage, de vérification et de construction. Elle ne doit jamais être présentée comme une autorité, une instance de contrôle ou un sujet auquel kOA délègue le jugement humain. Interdit dans les projections publiques : ```text IA gouvernable comme nom public principal faire gouverner l’IA donner le contrôle à l’IA déléguer la décision à l’IA présenter l’IA comme autorité finale ``` Autorisé : ```text Production augmentée par l’IA Production IA IA comme outil de construction IA comme atelier de travail responsabilité humaine validation humaine traces de travail preuves de vérification ``` --- # 9. Mapping Atlas → Faculty → Moodle ## 9.1 Mapping top-level | Atlas field | Faculty field | Moodle target | Règle | | ---------------------- | -------------------------------------------- | -------------------------------------- | ------------------------------- | | `voie_id` | `voie_id` | custom field `uckk_voie_id` | identique | | `code` | `moodle.course_prefix` | course idnumber prefix | cohérent | | `nom` | `identity.name` | category fullname | peut être adapté publiquement | | `domaine_operatoire` | `identity.domain` | custom field `uckk_domaine_operatoire` | identique ou override documenté | | `niveau_vise` | `identity.level` | custom field `uckk_niveau_vise` | identique | | `titre_symbolique` | `identity.title_symbolique` | custom field `uckk_titre_symbolique` | identique | | `statut` | `governance` / sync report | custom field `uckk_statut` | public seulement | | `definition_courte` | `atlas_projection` | course/category summary | dérivé | | `angle_fondamental` | `atlas_projection` | page/course summary | dérivé | | `competence_centrale` | `atlas_projection` | custom field or summary | dérivé | | `cours_conceptuels` | `atlas_projection.show_courses` | Moodle courses | généré si activé | | `projet_final` | `atlas_projection.show_projet_final` | capstone shell / summary | dérivé | | `limites_ethiques` | `atlas_projection.show_limites_ethiques` | notice/page summary | dérivé | | `relations_intervoies` | `atlas_projection.show_relations_intervoies` | related faculty cards | dérivé | | `tags` | `seo.keywords` / filters | custom field optional | optionnel | ## 9.2 Mapping cours | Atlas course field | Moodle course field | | --------------------------- | ------------------------------------------------------------- | | `cours_id` | `course.idnumber` and `course.shortname` | | `nom` | `course.fullname` | | `ordre` | course sort order | | `concept_maitre.concept_id` | custom field `uckk_concept_maitre_id` | | `concept_maitre.nom` | custom field `uckk_concept_maitre_nom` | | `artefact_maitrise.type` | custom field `uckk_artefact_type` | | `artefact_maitrise.nom` | custom field `uckk_artefact_nom` | | `criteres_passage` | completion criteria / rubric text, only if explicitly enabled | | `relations` | future graph links, report-only by default | ## 9.3 Convention `course.idnumber` ```text course.idnumber = cours_id course.shortname = cours_id course.fullname = cours_id + " — " + nom ``` Exemple : ```text GJS101 — Cartographie du Grand Jeu social ``` Règles : ```text course.idnumber est stable. course.shortname est stable. course.fullname peut être mis à jour depuis Atlas. course.idnumber ne doit jamais être dérivé d’un slug URL. course.idnumber ne doit jamais contenir d’espace. ``` ## 9.4 Convention catégorie ```text category.idnumber = category_idnumber category.name = identity.short_name ou Atlas nom normalisé category.description = résumé public filtré ``` Exemple : ```text category.idnumber = UCKK-GJS category.name = Grand Jeu social category.idnumber = UCKK-IA category.name = Production IA ``` ## 9.5 Convention hub course Chaque faculté peut avoir un cours hub. ```text CODE-HUB ``` Exemples : ```text GJS-HUB EC-HUB ECL-HUB SP-HUB LI-HUB ME-HUB IA-HUB IS-HUB AS-HUB KOA-HUB ``` Usage : ```text annonces publiques; événements publics; ressources publiques; orientation générale; lien vers les cours de la Voie; ateliers publics de production augmentée lorsque la voie concernée est Production IA. ``` Interdit : ```text notes privées; progression individuelle; badges personnels; preuves privées; dossiers étudiants. ``` --- # 10. Custom fields Moodle ## 10.1 Catégories Moodle Custom fields recommandés : ```text uckk_faculty_id uckk_voie_id uckk_code uckk_slug uckk_domaine_operatoire uckk_niveau_vise uckk_titre_symbolique uckk_statut uckk_schema_version uckk_faculty_profile_version uckk_atlas_source_hash uckk_faculty_source_hash ``` ## 10.2 Cours Moodle Custom fields recommandés : ```text uckk_cours_id uckk_voie_id uckk_faculty_id uckk_ordre uckk_concept_maitre_id uckk_concept_maitre_nom uckk_artefact_type uckk_artefact_nom uckk_reconnaissance_interne uckk_atlas_source_hash uckk_sync_status ``` ## 10.3 Badges / reconnaissances internes Convention recommandée : ```text UCKK-BADGE-{CODE}-PO ``` Exemples : ```text UCKK-BADGE-GJS-PO UCKK-BADGE-EC-PO UCKK-BADGE-ECL-PO UCKK-BADGE-SP-PO UCKK-BADGE-LI-PO UCKK-BADGE-ME-PO UCKK-BADGE-IA-PO UCKK-BADGE-IS-PO UCKK-BADGE-AS-PO UCKK-BADGE-KOA-PO ``` Règles : ```text Le badge est un shell de reconnaissance interne UCKK. Le sync ne doit pas attribuer le badge à un utilisateur. Le sync peut créer le badge shell seulement si l’option est explicitement activée. Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future. ``` --- # 11. Hashes de source ## 11.1 Objectif Les hashes permettent de détecter les changements sans logger tout le JSON. Chaque sync report doit inclure : ```text atlas_source_hash faculty_source_hash combined_source_hash ``` ## 11.2 Calcul recommandé ```text atlas_source_hash = sha256(JSON normalisé Atlas) faculty_source_hash = sha256(JSON normalisé Faculty) combined_source_hash = sha256(atlas_source_hash + ":" + faculty_source_hash) ``` ## 11.3 Règles ```text Ne pas logger le JSON complet. Ne pas logger les textes longs. Ne pas logger les données privées. Logger uniquement ids, status, counts, hashes, action summaries. ``` --- # 12. États de sync Valeurs autorisées pour `uckk_sync_status` : ```text not_synced validated dry_run_clean dry_run_warnings dry_run_blocked applied applied_with_warnings failed manual_review_required ``` Usage : | Status | Signification | | ------------------------ | ------------------------------------------ | | `not_synced` | Aucun sync connu | | `validated` | JSON valides, pas encore comparés à Moodle | | `dry_run_clean` | Aucun blocker, aucune action dangereuse | | `dry_run_warnings` | Sync possible avec warnings | | `dry_run_blocked` | Apply interdit | | `applied` | Apply terminé sans warning | | `applied_with_warnings` | Apply terminé avec warnings | | `failed` | Apply ou validation échoué | | `manual_review_required` | Intervention humaine requise | --- # 13. Types d’action dans un sync plan Valeurs autorisées : ```text create_category update_category create_hub_course update_hub_course create_course update_course create_custom_field update_custom_field create_badge_shell update_badge_shell purge_cache noop warning blocker ``` Interdits par défaut : ```text delete_category delete_course delete_badge delete_user_data enrol_user unenrol_user assign_role remove_role award_badge revoke_badge modify_grade modify_completion ``` --- # 14. Format du rapport de dry-run ## 14.1 Structure générale ```json { "schema_version": "UCKK-ATLAS-SYNC-REPORT-0.1", "mode": "dry_run", "status": "dry_run_clean", "generated_at": "2026-06-13T00:00:00Z", "component": "local_uckk", "source": { "atlas_manifest": "local/uckk/atlas/atlas_manifest.json", "faculty_manifest": "local/uckk/content/faculties/faculty_manifest.json" }, "counts": { "faculties_total": 10, "atlas_files_total": 10, "faculty_files_total": 10, "categories_create": 0, "categories_update": 0, "courses_create": 0, "courses_update": 0, "warnings": 0, "blockers": 0 }, "items": [], "warnings": [], "blockers": [], "hashes": { "atlas_manifest_hash": "", "faculty_manifest_hash": "", "combined_manifest_hash": "" } } ``` ## 14.2 Item de rapport ```json { "faculty_id": "faculty_grand_jeu_social", "voie_id": "voie_grand_jeu_social", "slug": "grand-jeu-social", "code": "GJS", "category_idnumber": "UCKK-GJS", "hub_course_idnumber": "GJS-HUB", "atlas_file": "voie_grand_jeu_social.json", "faculty_file": "grand-jeu-social.faculty.json", "status": "dry_run_clean", "source_hashes": { "atlas_source_hash": "", "faculty_source_hash": "", "combined_source_hash": "" }, "moodle_state": { "category_exists": true, "hub_course_exists": true, "course_count_expected": 10, "course_count_existing": 10 }, "actions": [ { "type": "noop", "target": "category", "idnumber": "UCKK-GJS", "message": "Category already aligned." } ], "warnings": [], "blockers": [] } ``` ## 14.3 Blocker ```json { "code": "missing_atlas_file", "severity": "blocker", "faculty_id": "faculty_grand_jeu_social", "voie_id": "voie_grand_jeu_social", "message": "Atlas file is listed in manifest but cannot be loaded." } ``` ## 14.4 Warning ```json { "code": "category_missing", "severity": "warning", "faculty_id": "faculty_grand_jeu_social", "voie_id": "voie_grand_jeu_social", "message": "Moodle category does not exist and would be created during apply." } ``` --- # 15. Format du rapport `apply` ```json { "schema_version": "UCKK-ATLAS-SYNC-REPORT-0.1", "mode": "apply", "status": "applied", "generated_at": "2026-06-13T00:00:00Z", "component": "local_uckk", "dry_run_required": true, "dry_run_hash": "", "counts": { "faculties_total": 10, "categories_created": 0, "categories_updated": 0, "hub_courses_created": 0, "hub_courses_updated": 0, "courses_created": 0, "courses_updated": 0, "badge_shells_created": 0, "badge_shells_updated": 0, "cache_purges": 0, "warnings": 0, "blockers": 0, "errors": 0 }, "items": [], "warnings": [], "errors": [], "hashes": { "atlas_manifest_hash": "", "faculty_manifest_hash": "", "combined_manifest_hash": "" } } ``` Règles : ```text apply doit référencer le dry_run_hash. apply doit refuser si le dry-run est stale. apply doit refuser si blockers > 0. apply doit refuser si capability absente. apply doit refuser si le mode source_atlas.sync_mode n’autorise pas la sync. ``` --- # 16. Blockers obligatoires Le sync doit bloquer si : ```text atlas_manifest.json invalide; faculty_manifest.json invalide; un fichier Atlas listé manque; un fichier Faculty listé manque; voie_id mismatch; faculty_id mismatch; slug mismatch; course_prefix mismatch; category_idnumber mismatch; schema_version inconnue; provider dynamic block inconnu; cours_conceptuels n’a pas exactement 10 cours; cours_id dupliqué; course idnumber cible déjà un cours non UCKK protégé; custom field requis absent et impossible à créer; permission manquante; sync_mode interdit; hash dry-run stale; tentative d’exposition de données privées; tentative d’inscription utilisateur; tentative de modification de note; tentative de suppression non autorisée. ``` --- # 17. Warnings recommandés Le sync peut warning si : ```text category Moodle absente mais créable; hub course absent mais créable; course absent mais créable; fullname Moodle diffère d’Atlas; description Moodle diffère de la projection publique; custom field optionnel absent; badge shell absent et badges activés; relations_intervoies non mappées; criteres_passage présents mais non publiés; concepts_associes masqués publiquement; cache désactivé. ``` --- # 18. Règles de création des catégories ## 18.1 Input minimal ```text faculty_id voie_id slug code category_idnumber identity.short_name identity.name identity.domain identity.level identity.title_symbolique ``` ## 18.2 Output Moodle attendu ```text course_categories.idnumber = category_idnumber course_categories.name = identity.short_name course_categories.description = résumé public filtré custom fields = métadonnées UCKK ``` ## 18.3 Règles ```text Ne pas créer deux catégories avec le même idnumber. Ne pas prendre possession d’une catégorie non UCKK sans validation humaine. Ne pas écraser une description manuelle si elle n’a pas été marquée gérée par UCKK. Ne pas utiliser category_id depuis JSON comme source principale. Préférer category_idnumber pour résolution stable. La description publique doit privilégier le savoir accessible, les parcours, les cours, les archives et l’apprentissage ouvert. ``` --- # 19. Règles de création des cours ## 19.1 Input minimal ```text cours_id ordre nom voie_id faculty_id code course_prefix category_idnumber concept_maitre.concept_id concept_maitre.nom artefact_maitrise.type artefact_maitrise.nom atlas_source_hash ``` ## 19.2 Output Moodle attendu ```text course.idnumber = cours_id course.shortname = cours_id course.fullname = cours_id + " — " + nom course.category = category resolved by category_idnumber course.visible = controlled by Faculty visibility rules course.format = uckk if available; otherwise site default course.customfields = UCKK metadata ``` ## 19.3 Règles ```text Ne pas changer idnumber d’un cours existant. Ne pas déplacer un cours existant non UCKK sans validation humaine. Ne pas écraser du contenu pédagogique manuel. Ne pas supprimer activités existantes. Ne pas créer inscriptions. Ne pas modifier achèvements. Ne pas modifier notes. Le résumé public du cours doit rester orienté vers l’apprentissage, les ressources, les concepts, les pratiques et les traces utiles. ``` --- # 20. Règles de création du cours hub ## 20.1 Input minimal ```text hub_course_idnumber category_idnumber identity.name identity.short_name hero.summary dynamic_blocks ``` ## 20.2 Output Moodle attendu ```text course.idnumber = CODE-HUB course.shortname = CODE-HUB course.fullname = "Hub — " + identity.short_name course.category = category resolved by category_idnumber course.visible = true if profile is public or restricted ``` ## 20.3 Rôle Le hub peut porter : ```text annonces; calendrier public; ressources publiques; orientation générale; liens vers les cours; liens vers la médiathèque; liens vers les archives publiques. ``` Le hub ne doit pas porter : ```text notes privées; progression individuelle; preuves privées; votes privés; dossiers personnels. ``` --- # 21. Règles de badges / reconnaissances internes ## 21.1 Badge shell Le sync peut préparer un badge shell de Voie si l’option est explicitement activée. Convention : ```text idnumber = UCKK-BADGE-{CODE}-PO name = Reconnaissance interne — {identity.short_name} ``` ## 21.2 Interdictions Le sync ne doit jamais : ```text attribuer un badge; révoquer un badge; publier une liste de détenteurs; exposer des preuves privées; déduire un achèvement depuis un JSON; présenter une reconnaissance interne comme une certification formelle externe. ``` ## 21.3 Formule publique unique Si une note de reconnaissance doit être affichée publiquement, utiliser une seule formule courte : ```text Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future. ``` Cette phrase ne doit pas devenir le thème principal d’une page publique. --- # 22. Règles de visibilité ## 22.1 Faculty visibility | Faculty `visibility` | Effet sync recommandé | | -------------------- | --------------------------------------------------------------------------- | | `public` | category/course shells publics ou visibles selon Moodle policy | | `hidden` | ne pas afficher publiquement; sync possible mais visibilité Moodle prudente | | `restricted` | accès via login/capability; pas d’exposition publique anonyme | ## 22.2 Enrolment visibility | `enrolment_visibility` | Effet | | ---------------------- | ----------------------------------------------------------- | | `hidden` | ne pas afficher les liens Moodle | | `public_info_only` | afficher programme public, pas d’inscription auto | | `login_required` | lien visible après login | | `enrolment_required` | lien visible seulement aux inscrits si contrôlé côté Moodle | --- # 23. Services internes ## 23.1 `voie_repository` Responsabilités : ```text résoudre chemin Atlas depuis manifest; charger JSON; refuser chemin arbitraire; retourner données brutes; ne pas mapper Moodle; ne pas valider permissions. ``` ## 23.2 `voie_validator` Responsabilités : ```text valider schema_version; valider champs obligatoires; valider cours_conceptuels length = 10; valider cours_id; valider ordre 1..10; valider concept_maitre; valider concepts_associes; retourner erreurs/warnings structurés. ``` ## 23.3 `voie_normalizer` Responsabilités : ```text ordonner cours_conceptuels par ordre; normaliser chaînes; normaliser listes vides; calculer hash source; préparer modèle stable pour diff. ``` ## 23.4 `voie_moodle_mapper` Responsabilités : ```text mapper Atlas normalisé vers catégories/cours/custom fields; produire expected Moodle model; produire action candidates; ne pas écrire en base directement sauf méthode apply explicitement documentée; ne jamais gérer permissions utilisateur. ``` ## 23.5 `faculty_repository` Responsabilités : ```text charger Faculty JSON depuis manifest; refuser chemin arbitraire; retourner données brutes; ne pas rendre Mustache; ne pas appeler Moodle write APIs. ``` ## 23.6 `faculty_validator` Responsabilités : ```text valider schema_version; valider slug; valider source_atlas; valider moodle; valider navigation; valider dynamic_blocks; valider providers; valider guardrails; retourner erreurs/warnings structurés. ``` ## 23.7 `faculty_normalizer` Responsabilités : ```text normaliser status; normaliser visibility; normaliser anchors; normaliser dynamic_blocks; calculer hash source; préparer modèle stable. ``` ## 23.8 `faculty_moodle_mapper` Responsabilités : ```text mapper Faculty normalisé vers category metadata; mapper hub course; mapper public visibility; mapper dynamic block source references; produire expected Moodle model. ``` --- # 24. CLI ## 24.1 Validation ```bash php local/uckk/cli/validate_faculties.php ``` Doit vérifier : ```text atlas manifest; faculty manifest; 10 Atlas JSON; 10 Faculty JSON; correspondances; providers; anchors; guardrails; source_atlas.sync_mode. ``` ## 24.2 Dry-run sync ```bash php local/uckk/cli/sync_atlas.php --mode=dry_run ``` Options recommandées : ```text --mode=dry_run --faculty=grand-jeu-social --all --json --verbose ``` ## 24.3 Apply sync ```bash php local/uckk/cli/sync_atlas.php --mode=apply --confirm=1 ``` Règles : ```text apply exige confirm=1; apply exige validation complète; apply doit refuser blockers; apply doit produire rapport; apply doit émettre event. ``` ## 24.4 Report ```bash php local/uckk/cli/sync_atlas.php --mode=report --json ``` --- # 25. Contrôleur admin Fichier : ```text local/uckk/faculty_sync.php ``` Responsabilités : ```text require_login(); require_capability('local/uckk:syncatlasmoodle', context_system::instance()); afficher formulaire de mode; lancer validation/dry-run/apply; afficher rapport; ne pas accepter chemin de fichier depuis URL; ne pas exposer JSON brut. ``` Paramètres autorisés : ```text mode faculty confirm sesskey format ``` Paramètres interdits : ```text path file dir json raw callback ``` --- # 26. Services externes ## 26.1 `local_uckk_run_atlas_sync_dryrun` Usage : ```text lancer dry-run depuis interface admin ou service autorisé. ``` Exigences : ```text db/services.php; classes/external/run_atlas_sync_dryrun.php; validation stricte des paramètres; capability local/uckk:syncatlasmoodle; retour typé; aucun apply. ``` ## 26.2 `local_uckk_get_faculty_sync_report` Usage : ```text retourner un rapport de sync filtré. ``` Exigences : ```text capability local/uckk:viewfacultysyncreport; ne pas retourner JSON source complet; ne pas retourner données privées; retourner ids, status, actions, warnings, blockers, hashes. ``` --- # 27. Events ## 27.1 `atlas_voie_validated` Déclenché quand : ```text un JSON Atlas est validé. ``` Données autorisées : ```text voie_id; code; status; error_count; warning_count; atlas_source_hash. ``` Données interdites : ```text contenu JSON complet; données privées; texte long pédagogique complet. ``` ## 27.2 `atlas_sync_dryrun_completed` Déclenché quand : ```text un dry-run est terminé. ``` Données autorisées : ```text mode; status; faculty_count; action_count; warning_count; blocker_count; combined_manifest_hash. ``` ## 27.3 `atlas_sync_applied` Déclenché quand : ```text un apply est terminé. ``` Données autorisées : ```text mode; status; created_count; updated_count; warning_count; error_count; combined_manifest_hash. ``` --- # 28. Cache Caches concernés : ```text local_uckk/atlas_manifest local_uckk/atlas_voie local_uckk/faculty_manifest local_uckk/faculty_profile local_uckk/faculty_page local_uckk/faculty_dynamic_block local_uckk/faculty_sync_report ``` Règles : ```text validate ne purge pas. dry_run peut écrire ou rafraîchir un rapport cache si configuré. apply purge faculty_page et faculty_dynamic_block pour les facultés touchées. purge manuelle exige CAP_PURGE_FACULTY_CACHE. ``` --- # 29. Sécurité ## 29.1 Chemins Interdit : ```text accepter un chemin depuis l’URL; charger un fichier hors manifest; résoudre ../; résoudre chemin absolu; utiliser slug comme chemin. ``` Autorisé : ```text slug → faculty_manifest → faculty_file; voie_id → atlas_manifest → atlas_file. ``` ## 29.2 Permissions Règles : ```text Public page ≠ sync permission. Faculty editor ≠ Moodle admin. Symbolic title ≠ capability. Reconnaissance interne ≠ permission. ``` ## 29.3 Données privées Le sync ne doit pas lire ou écrire : ```text notes; progression individuelle; achèvements individuels; dossiers personnels; preuves privées; votes privés; feedback privé; badges personnels affichés publiquement. ``` --- # 30. Stratégie de diff ## 30.1 Diff catégorie Comparer : ```text category.idnumber; category.name; category.description; custom fields UCKK; visibility policy. ``` Ne pas comparer : ```text champs Moodle non UCKK; contenu manuel non marqué managed_by=local_uckk; statistiques; inscriptions. ``` ## 30.2 Diff cours Comparer : ```text course.idnumber; course.shortname; course.fullname; course.category; course.visible; custom fields UCKK; source hash. ``` Ne pas comparer : ```text sections manuelles; activités non générées; notes; achèvement; enrolments; logs. ``` ## 30.3 Diff badge shell Comparer : ```text badge.idnumber; badge.name; badge.description publique; issuer; status shell. ``` Ne pas comparer : ```text awards; recipients; evidence; endorsements personnels. ``` --- # 31. Compatibilité avec `tool_uckkseed` `local_uckk` peut préparer un modèle Moodle attendu. `tool_uckkseed` peut être utilisé plus tard pour appliquer des catégories, cours, champs custom, badges ou compétences depuis des presets. Règle : ```text local_uckk garde le contrat Atlas/Faculty/Moodle. tool_uckkseed garde les opérations de seed génériques. Aucun des deux ne doit contourner validation, dry-run ou capabilities. ``` Quand `tool_uckkseed` est utilisé : ```text local_uckk produit le plan ou preset dérivé; tool_uckkseed valide le preset; tool_uckkseed dry-run; tool_uckkseed apply; local_uckk lit le résultat et met à jour le sync report. ``` --- # 32. Compatibilité avec `format_uckk` `format_uckk` peut rendre les cours Moodle selon l’identité UCKK. Règle : ```text local_uckk ne doit pas injecter de logique de format de cours. format_uckk ne doit pas devenir source de vérité Atlas. format_uckk doit servir l’apprentissage, l’orientation, les ressources et les traces utiles. ``` --- # 33. Compatibilité avec `theme_uckk` `theme_uckk` fournit l’identité visuelle publique. Règle : ```text theme_uckk ne contient pas de logique de sync. theme_uckk ne lit pas directement les JSON Atlas. theme_uckk ne valide pas les profiles Faculty. theme_uckk doit soutenir la lisibilité publique, pas remplacer la couche éditoriale. ``` --- # 34. Compatibilité avec `report_uckk` `report_uckk` peut afficher des rapports de cohérence. Règle : ```text local_uckk produit les données de sync. report_uckk peut les lire ou les présenter. report_uckk ne doit pas appliquer de sync. ``` --- # 35. Tests obligatoires ## 35.1 PHPUnit Fichiers concernés : ```text local/uckk/tests/atlas_manifest_test.php local/uckk/tests/voie_repository_test.php local/uckk/tests/voie_validator_test.php local/uckk/tests/voie_normalizer_test.php local/uckk/tests/faculty_manifest_test.php local/uckk/tests/faculty_registry_test.php local/uckk/tests/faculty_repository_test.php local/uckk/tests/faculty_validator_test.php local/uckk/tests/faculty_moodle_mapper_test.php local/uckk/tests/faculty_cache_test.php ``` Tests sync recommandés : ```text manifest Atlas valide; manifest Faculty valide; 10 facultés présentes; 10 JSON Atlas chargés; 10 JSON Faculty chargés; mismatch voie_id bloque; mismatch slug bloque; provider inconnu bloque; cours_conceptuels != 10 bloque; dry-run ne modifie pas Moodle; apply refuse sans capability; apply refuse si blockers; hash source change si JSON change; course idnumber convention respectée; category_idnumber convention respectée; private data never appears in report. ``` ## 35.2 Behat Fichiers concernés : ```text local/uckk/tests/behat/faculty_sync_dryrun.feature local/uckk/tests/behat/faculty_admin_validation.feature ``` Scénarios recommandés : ```text admin launches dry-run for all faculties; admin sees blockers; admin cannot apply blocked sync; non-admin cannot access sync page; dry-run report does not show raw JSON; public user cannot access sync page; cache purge event appears after apply. ``` --- # 36. Commandes de validation statique Depuis la racine du dépôt : ```bash find . -name '*.php' -not -path './vendor/*' -print0 | xargs -0 -n1 php -l ``` ```bash find . -name '*.json' -print0 | xargs -0 -n1 python3 -m json.tool >/dev/null ``` ````bash grep -RIn --include='*.php' '```' local/uckk || true ```` ```bash grep -RIn --include='*.js' '", "version": 2026051200, "items": [] } ```` Optional top-level `metadata` is allowed: ```json { "metadata": { "source_family": "UCKK canon", "generated_at": "2026-05-19T00:00:00-04:00", "notes": [] } } ``` The following envelope is **not** valid as the active runtime seed envelope: ```json { "schema_version": "1.0", "preset_type": "courses", "source_family": "UCKK canon", "items": [] } ``` Those fields may be preserved only inside top-level `metadata`. --- ## 3. Presets governed by this reference ```text academic_registry_json/categories.json academic_registry_json/programs.json academic_registry_json/pathways.json academic_registry_json/cohorts.json academic_registry_json/roles.json academic_registry_json/capabilities.json academic_registry_json/competencies.json academic_registry_json/badges.json academic_registry_json/course_templates.json academic_registry_json/challenge_templates.json academic_registry_json/assembly_templates.json academic_registry_json/archive_templates.json academic_registry_json/courses.json academic_registry_json/reports.json ``` The current snapshot contains these 14 files. Final `tool_uckkseed` must treat all 14 as part of the governed registry. --- ## 4. Final handler routing Final `tool_uckkseed` must support these presets and handlers: | Preset | JSON file | Final handler | Owner / target | | --------------------- | -------------------------- | ------------------------- | ------------------------------------------- | | `categories` | `categories.json` | `category_seed` | Moodle course categories | | `programs` | `programs.json` | `program_seed` | `local_uckk_program` | | `cohorts` | `cohorts.json` | `cohort_seed` | Moodle cohorts | | `roles` | `roles.json` | `role_seed` | Moodle roles and embedded role capabilities | | `capabilities` | `capabilities.json` | `capability_seed` | Moodle role capability assignments | | `competencies` | `competencies.json` | `competency_seed` | Moodle core competency framework | | `course_templates` | `course_templates.json` | `course_template_seed` | seed-managed course templates | | `challenge_templates` | `challenge_templates.json` | `challenge_template_seed` | `mod_uckkchallenge` template definitions | | `assembly_templates` | `assembly_templates.json` | `assembly_template_seed` | `mod_uckkassembly` template definitions | | `archive_templates` | `archive_templates.json` | `archive_template_seed` | `mod_uckkarchive` template definitions | | `courses` | `courses.json` | `course_seed` | Moodle courses | | `badges` | `badges.json` | `badge_seed` | Moodle badges | | `pathways` | `pathways.json` | `pathway_seed` | `local_uckk_pathway` | | `reports` | `reports.json` | `report_seed` | `report_uckk` seeded report definitions | ### Final default validation/seed order The default order must satisfy hard database dependencies first and allow soft cross-preset references to resolve by stable JSON keys during validation. ```text categories programs cohorts roles capabilities competencies course_templates challenge_templates assembly_templates archive_templates courses badges pathways reports ``` ### Soft-reference rule Some preset families refer to each other conceptually before every Moodle object exists. These references are allowed as stable JSON references during validation and dry run: ```text badges may reference programs, pathways, courses, and competencies by stable JSON key/id/idnumber. pathways may reference courses, competencies, and badges by stable JSON key/id/idnumber. ``` Validation may warn when a referenced object does not yet exist in Moodle storage, but it must not fail only because a soft reference is resolved from another preset file rather than from the database. Apply mode must be idempotent and safe to rerun. ### Current implementation gap `seeder.php` and the individual `*_seed.php` handlers are the authoritative runtime routing layer. All entry points must expose the same governed preset registry: ```text cli/seed.php cli/reset.php cli/export_preset.php classes/form/seed_form.php classes/form/reset_form.php ``` If any entry point omits `programs` or `pathways`, that entry point is incomplete even if direct `validate.php --preset=programs` or `validate.php --preset=pathways` works. --- ## 5. Common item rules ### 5.1 Stable `key` Every item must have a stable `key` unless the handler explicitly uses a different required key. ```json { "key": "uckk_tc101" } ``` Rules: * lowercase snake case or compact stable identifier preferred * no runtime database ids * no translated label as the only identifier * may be used in metadata, config markers, rollback plans, and audit logs ### 5.2 Stable canonical `id` Every item should have a semantic `id` when the source JSON already carries one. Examples: ```text program:tronc-commun pathway:tronc-commun-main course:uckk-tc101 badge:tronc-commun-completion competency:tronc-commun:synthesis ``` Canonical ids must be stored in `metadata` when the Moodle target table has no dedicated column. ### 5.3 Moodle reconciliation identifiers Handlers should prefer this reconciliation order: 1. Moodle/native idnumber or shortname when available. 2. Seed-managed metadata marker. 3. Config marker owned by `tool_uckkseed`. 4. Name/title only as last resort and only when safe. No handler may depend on transient numeric ids from JSON. ### 5.4 Status and visibility JSON presets may contain domain statuses. Handlers must either: * accept the value directly; * map it to a storage-safe value; or * validate and reject it with an explicit message. Handlers must not silently discard status/visibility fields. ### 5.5 Metadata `metadata` is allowed for every item. It must remain JSON-serializable and deterministic. ### 5.6 AI metadata AI metadata is allowed only as provenance or drafting context. Allowed: ```json { "metadata": { "ai_assisted": true, "review_state": "human_reviewed", "source_prompt": "..." } } ``` Not allowed: * automatic grading authority * automatic badge award authority * automatic competency certification authority * automatic integrity closure authority * automatic archive validation authority AI metadata is non-authoritative unless a human-controlled handler explicitly uses it. --- # 6. Preset contracts --- ## 6.1 `categories.json` **Preset:** `categories` **Handler:** `category_seed` **Moodle owner:** course categories **Idempotency key:** `idnumber` ### Required item fields ```json { "key": "UCKK-TC", "idnumber": "UCKK-TC", "name": "Tronc commun obligatoire", "parent": "", "visible": 1, "sortorder": 10, "description": "...", "metadata": {} } ``` ### Accepted aliases Handlers should accept: | Canonical | Accepted aliases | | ---------- | ------------------------------------------ | | `idnumber` | `key`, `category_idnumber` | | `name` | `title`, `fullname` | | `parent` | `parent_idnumber`, `parent_category` | | `visible` | `visibility` when numeric/boolean mappable | ### Required category idnumbers for the current course set The active `courses.json` and `programs.json` reference these category idnumbers: ```text UCKK-TC UCKK-GJS UCKK-KOA UCKK-AS UCKK-SP UCKK-ME UCKK-LI UCKK-LEAD UCKK-ARCH UCKK-UX UCKK-ETHIC UCKK-IA ``` `categories.json` must include those before course/program validation is considered complete. ### Validation rules * `idnumber` required and unique. * `name` required. * `parent`, when present, must reference another seeded category idnumber or an existing Moodle category idnumber. * No category may create a cycle. * `idnumber` must fit Moodle `course_categories.idnumber`. --- ## 6.2 `programs.json` **Preset:** `programs` **Final handler:** `program_seed` **Moodle/local owner:** `local_uckk` **Table:** `local_uckk_program` **Idempotency key:** `shortname`; `idnumber` should also be unique in the JSON even if not a table column. `programs.json` is seedable in the final target. It is not canon-only. ### Required item fields ```json { "key": "tronc_commun", "id": "program:tronc-commun", "code": "TC", "shortname": "TC", "idnumber": "UCKK-PROG-TC", "name": "Tronc commun obligatoire", "fullname": "Tronc commun obligatoire", "program_type": "tronc_commun", "category": "UCKK-TC", "category_idnumber": "UCKK-TC", "description": "...", "summary": "...", "status": "active", "visibility": "institution", "visible": 1, "sortorder": 10, "domain": {}, "palier": {}, "recognition": {}, "tags": [], "metadata": {} } ``` ### Storage mapping | JSON field | `local_uckk_program` column | | ---------------------------------- | --------------------------------------------------------------------- | | `shortname` | `shortname` | | `fullname` / `name` / `title` | `fullname` | | `program_type` | `programtype` | | `category` / `category_idnumber` | resolves to `categoryid` | | `description` / `summary` | `description` | | `sortorder` | `sortorder` | | `status` | `status` | | `visibility` | `visibility` | | generated seed context | `contextid`, `createdby`, `modifiedby`, `timecreated`, `timemodified` | | `metadata` plus extra canon fields | `metadata` | ### Program type vocabulary Final handlers should accept current JSON/source vocabulary and map it to local storage values where needed. Recommended JSON values: ```text tronc_commun voie_uckk mineure seminaire laboratoire orientation palier parcours_transversal ``` Local model values include: ```text tronccommun baccalaureat mineure lab seminar transversal ``` ### Runtime status vocabulary `program_seed` must either accept or normalize every status used by `programs.json`. The safe runtime vocabulary is: ```text draft active hidden archived pending pending_review validated rejected correction_required contested invalidated closed cancelled completed blocked ``` `internal_experimental` is not a valid runtime status unless `program_seed` is explicitly extended to accept it. Experimental programs should use `draft` unless the lifecycle vocabulary is intentionally expanded. ### Validation rules * `key`, `shortname`, `fullname`, `program_type`, and `status` required. * `category` must reference an existing `categories.idnumber` when present. * `code`, `shortname`, and `idnumber` must be unique within `programs.json`. * Public accreditation disclaimers remain description/metadata content, not role/capability logic. --- ## 6.3 `pathways.json` **Preset:** `pathways` **Final handler:** `pathway_seed` **Moodle/local owner:** `local_uckk` **Table:** `local_uckk_pathway` **Idempotency key:** `programid + shortname`; `idnumber` should also be unique in the JSON. `pathways.json` is seedable in the final target. It is not canon-only. ### Required item fields ```json { "key": "tronc_commun_main", "id": "pathway:tronc-commun-main", "idnumber": "UCKK-PATH-TRONC-COMMUN-MAIN", "shortname": "tronc_commun_main", "name": "Parcours principal — Tronc commun obligatoire", "fullname": "Parcours principal — Tronc commun obligatoire", "program_id": "program:tronc-commun", "program_code": "TC", "pathway_type": "ordered_courses", "sequence_model": "ordered_courses", "status": "active", "visibility": "institution", "sortorder": 10, "prerequisite_pathway_refs": [], "cycles": [], "completion_rule": {}, "competency_refs": [], "badge_refs": [], "evidence_requirements": [], "metadata": {} } ``` ### Storage mapping | JSON field | `local_uckk_pathway` column | | ------------------------------------------------------------- | --------------------------------------------------------------------- | | `program_id` / `program_code` | resolves to `programid` | | `shortname` | `shortname` | | `fullname` / `name` / `title` | `fullname` | | `pathway_type` / `sequence_model` | `pathwaytype` | | flattened required course ids from `cycles[].course_refs[]` | `requiredcourseids` | | `badge_refs` | `requiredbadges` | | `competency_refs` | `requiredcompetencies` | | `description` | `description` | | `sortorder` | `sortorder` | | `status` | `status` | | `visibility` | `visibility` | | generated seed context | `contextid`, `createdby`, `modifiedby`, `timecreated`, `timemodified` | | `metadata` plus `cycles`, `completion_rule`, evidence details | `metadata` | ### Course reference shape Inside each `cycles[].course_refs[]`: ```json { "course_id": "course:uckk-tc101", "course_code": "UCKK-TC101", "requirement": "required", "sequence": 1, "recognition_mode": "program_specific", "variant_group": "variant:..." } ``` ### Recommended vocabularies `sequence_model` / `pathway_type`: ```text ordered_courses cycles phases modules portfolio_based tronc_commun baccalaureat mineure seminaire laboratoire ``` `requirement`: ```text required optional advanced_option final_project portfolio challenge assembly_participation ``` `recognition_mode`: ```text shared_course program_specific specialized_variant equivalent external_recognition_pending ``` ### Validation rules * `program_id` must match a seeded program `id`, or `program_code` must match a seeded program `code`. * `course_code` must match a seeded course `code`/`idnumber`, or `course_id` must match a seeded course `id`. * `badge_refs` must match seeded badge `id`, `idnumber`, or `key` from `badges.json`, or an existing Moodle badge identifier when available. * `competency_refs` must match seeded competency `id`, `idnumber`, or `key`. * `cycles[].course_refs[]` must be ordered and deterministic. * Validation must not require Moodle's `badge` table to contain non-core/generated columns such as `uniquehash`. When badge columns are inspected, the handler must first check the installed table schema. --- ## 6.4 `cohorts.json` **Preset:** `cohorts` **Handler:** `cohort_seed` **Moodle owner:** Moodle cohorts **Idempotency key:** `idnumber` ### Required item fields ```json { "key": "UCKK-TC-Aspirants", "idnumber": "UCKK-TC-Aspirants", "name": "Aspirants — Tronc commun", "context": "system", "description": "...", "visible": 1, "metadata": {} } ``` ### Validation rules * `idnumber` required and unique. * `name` required. * `context` must be `system`, `category`, or `course`. * Category/course contexts must reference valid seeded/existing category/course ids. --- ## 6.5 `roles.json` **Preset:** `roles` **Handler:** `role_seed` **Moodle owner:** Moodle roles **Idempotency key:** `shortname` ### Required item fields ```json { "key": "uckklearner", "shortname": "uckklearner", "name": "UCKK learner", "description": "...", "archetype": "student", "contextlevels": ["course"], "permissions": [], "metadata": {} } ``` ### Technical role shortnames Seeded Moodle roles must remain technical roles, not symbolic identities. Allowed technical role examples: ```text uckklearner uckkmentor uckkmanager uckkarchivist uckkintegrityofficer uckkassemblyfacilitator uckkauditor ``` Symbolic titles such as `Le Mage`, `Inquisiteur`, `Architecte`, `Cartographe`, `Archiviste mythique` must remain profile, badge, cohort, pathway, or display metadata, not Moodle role shortnames. ### Permission values ```text allow prevent prohibit inherit ``` ### Allowed context levels ```text system user category course module block ``` Handler must map these to Moodle context constants. --- ## 6.6 `capabilities.json` **Preset:** `capabilities` **Handler:** `capability_seed` **Moodle owner:** Moodle role capability assignments **Idempotency key:** `role + capability` ### Required item fields ```json { "key": "uckkmanager:local/uckk:manageprograms", "role": "uckkmanager", "capability": "local/uckk:manageprograms", "permission": "allow", "context": "system", "metadata": {} } ``` ### Validation rules * `role` must reference a seeded/existing role shortname. * `capability` must exist in Moodle core or plugin `db/access.php`. * `permission` must be `allow`, `prevent`, `prohibit`, or `inherit`. * `context` must be valid for the target capability. * Capability context mismatches must be reported as warnings or errors depending on strictness. ### Allowed UCKK capability prefixes ```text local/uckk: block/uckk_dashboard: mod/uckkchallenge: mod/uckkassembly: mod/uckkarchive: tool/uckkintegrity: report/uckk: format/uckk: theme/uckk: aiprovider/uckk: ``` --- ## 6.7 `competencies.json` **Preset:** `competencies` **Handler:** `competency_seed` **Moodle owner:** Moodle core competency framework **Idempotency key:** framework idnumber + competency idnumber ### Required item fields ```json { "key": "UCKK-COMP-TC-SYNTHESIS", "idnumber": "UCKK-COMP-TC-SYNTHESIS", "shortname": "Synthesis", "description": "...", "framework": "UCKK-COMP", "parent": "", "sortorder": 10, "scale": "defaultcompetencescale", "metadata": {} } ``` ### Object types `competencies.json` may contain both framework and competency rows. Use `object_type` when needed: ```text framework competency ``` ### Validation rules * Framework idnumber required for frameworks. * Competency idnumber required for competencies. * Current and final handlers must accept UCKK competency idnumbers matching: ```text ^UCKK-COMP-[A-Z0-9-]+$ ``` * Parent references must resolve within the same preset or existing Moodle competency storage. * AI-generated competency descriptions are metadata/provenance only. --- ## 6.8 `badges.json` **Preset:** `badges` **Handler:** `badge_seed` **Moodle owner:** Moodle badges **Idempotency key:** `key`; `idnumber` should also be unique. ### Required item fields ```json { "key": "tronc_commun_completion", "id": "badge:tronc-commun-completion", "object_type": "badge", "idnumber": "UCKK-BADGE-TC-COMPLETION", "name": "Socle commun UCKK — Joueur lucide en formation", "title": "Socle commun UCKK — Joueur lucide en formation", "short_title": "Tronc commun", "description": "...", "type": "site", "badge_type": "tronc_commun_completion", "status": "active", "visible": 1, "enabled": 1, "program_id": "program:tronc-commun", "pathway_id": "pathway:tronc-commun-main", "criteria": [ "pathway_completion", "human_validation", "competency_threshold", "archive_or_portfolio", "no_unresolved_integrity_block" ], "competencies": ["UCKK-COMP-TC-SYNTHESIS"], "linked_competency_ids": ["competency:tronc-commun:synthesis"], "linked_course_ids": { "required": [], "optional": [], "final_project": [] }, "award_criteria": [], "requiredarchive": true, "requireshumanvalidation": true, "issuer": {}, "metadata": {} } ``` ### Required badge criteria vocabulary Final badge seed logic must support these criteria: ```text pathway_completion course_completion evidence_submission human_validation competency_threshold archive_or_portfolio no_unresolved_integrity_block assembly_participation challenge_completion ``` ### Moodle badge schema compatibility `badge_seed` must use Moodle's installed badge schema as the source of truth. Seed ownership must not depend on a required `badge.uniquehash` column. The handler may use optional/generated columns only after checking that they exist in the installed table. Seed-managed badges should be reconciled by stable JSON `key` / `idnumber` and plugin-owned config markers such as: ```text tool_uckkseed.badge__id tool_uckkseed.badge__definition ``` This keeps the seed tool compatible with Moodle installations whose `badge` table does not contain `uniquehash`. ### Validation rules * `key`, `name`, `description`, and `type` required. * `type` must be `site` or `course` unless the handler is explicitly extended. * `key` must be unique. * `idnumber`, when present, must be unique. * `competencies` should use competency `idnumber` values. * `linked_competency_ids` may preserve canonical competency `id` values. * `linked_course_ids` may preserve canonical course `id` values; seed logic must resolve them through course `id`, `code`, or `idnumber`. * Program completion badges and pathway completion badges are first-class final seed objects. * Symbolic legacy badges may exist, but are not the only supported badge family. --- ## 6.9 `course_templates.json` **Preset:** `course_templates` **Handler:** `course_template_seed` **Moodle owner:** seed-managed template definitions **Idempotency key:** `key` ### Required item fields ```json { "key": "uckk_standard_course", "name": "UCKK standard course", "description": "...", "format": "uckk", "sections": [], "activities": [], "completion_defaults": {}, "metadata": {} } ``` ### Validation rules * `key` required and unique. * `name` required. * Template validation must not create Moodle courses. * Template presets must not be routed through `course_seed`. * Activity component references must be optional unless strict mode is enabled. --- ## 6.10 `challenge_templates.json` **Preset:** `challenge_templates` **Handler:** `challenge_template_seed` **Moodle owner:** `mod_uckkchallenge` template definitions **Idempotency key:** `key` ### Required item fields ```json { "key": "uckk_reflection_challenge", "name": "UCKK reflection challenge", "description": "...", "visibility": "institution", "sections": [], "requirements": [], "metadata": {} } ``` ### Validation rules * `key` required and unique. * `name` required. * Sections should have stable `key` or deterministic `number`. * Badge, competency, and role references must resolve when strict mode is used. * Challenge templates must not create course activities directly unless apply mode explicitly instantiates them. --- ## 6.11 `assembly_templates.json` **Preset:** `assembly_templates` **Handler:** `assembly_template_seed` **Moodle owner:** `mod_uckkassembly` template definitions **Idempotency key:** `key` ### Required item fields ```json { "key": "uckk_deliberation_assembly", "name": "UCKK deliberation assembly", "description": "...", "visibility": "institution", "validationstate": "draft", "roles": [], "steps": [], "metadata": {} } ``` ### Validation rules * `key` required and unique. * `name` required. * `visibility` must be in the handler vocabulary. * `validationstate` must be in the handler vocabulary. * Human review state must not be treated as AI authority. --- ## 6.12 `archive_templates.json` **Preset:** `archive_templates` **Handler:** `archive_template_seed` **Moodle owner:** `mod_uckkarchive` template definitions **Idempotency key:** `key` ### Required item fields ```json { "key": "uckk_archive_portfolio", "name": "UCKK archive portfolio", "description": "...", "defaults": { "visibility": "private" }, "fields": [], "metadata": {} } ``` ### Validation rules * `key` required and unique. * `name` required. * `defaults.visibility` must be in the archive handler vocabulary. * Archive templates must not validate archive evidence directly. * Privacy and retention policy metadata must remain explicit. --- ## 6.13 `courses.json` **Preset:** `courses` **Handler:** `course_seed` **Moodle owner:** Moodle courses **Idempotency key:** `shortname`; `idnumber` should also be unique. ### Required item fields ```json { "key": "uckk_tc101", "id": "course:uckk-tc101", "shortname": "UCKK-TC101", "idnumber": "UCKK-TC101", "fullname": "UCKK TC101 — Introduction", "category": "UCKK-TC", "category_idnumber": "UCKK-TC", "format": "uckk", "visible": 1, "summary": "...", "metadata": {} } ``` ### Validation rules * `shortname` required and unique. * `fullname` required. * `category` / `category_idnumber` must resolve to `categories.idnumber` or existing Moodle category idnumber. * `summaryformat` must be numeric or safely normalized. * `format` must be installed or safely default to Moodle format. * Course creation must not automatically enrol users unless explicitly configured. * Course creation must not automatically award badges or certify competencies. --- ## 6.14 `reports.json` **Preset:** `reports` **Handler:** `report_seed` **Moodle owner:** `report_uckk` **Idempotency key:** `key` ### Required item fields ```json { "key": "uckk_program_progress", "name": "UCKK program progress", "capability": "report/uckk:view", "description": "...", "metadata": {} } ``` ### Allowed report capabilities ```text report/uckk:view report/uckk:viewown report/uckk:viewall report/uckk:export ``` ### Validation rules * `key` required and unique. * `name` required. * `capability` required. * `capability` must exist in `report/uckk/db/access.php`. * Report definitions must not expose restricted integrity/archive data without explicit capabilities. --- # 7. Capability registry This reference recognizes the following UCKK capability families. ## 7.1 `local_uckk` ```text local/uckk:view local/uckk:manage local/uckk:manageprograms local/uckk:viewprograms local/uckk:managepathways local/uckk:viewpathways local/uckk:manageprofiles local/uckk:viewprofiles local/uckk:managecanon local/uckk:viewcanon local/uckk:assignpathways local/uckk:viewreports ``` ## 7.2 `block_uckk_dashboard` ```text block/uckk_dashboard:view block/uckk_dashboard:viewothers block/uckk_dashboard:configure block/uckk_dashboard:addinstance block/uckk_dashboard:myaddinstance ``` ## 7.3 `mod_uckkchallenge` ```text mod/uckkchallenge:view mod/uckkchallenge:addinstance mod/uckkchallenge:submit mod/uckkchallenge:grade mod/uckkchallenge:manage mod/uckkchallenge:viewallsubmissions mod/uckkchallenge:validate mod/uckkchallenge:override ``` ## 7.4 `mod_uckkassembly` ```text mod/uckkassembly:view mod/uckkassembly:addinstance mod/uckkassembly:participate mod/uckkassembly:facilitate mod/uckkassembly:manage mod/uckkassembly:viewall mod/uckkassembly:recorddecision mod/uckkassembly:publish ``` ## 7.5 `mod_uckkarchive` ```text mod/uckkarchive:view mod/uckkarchive:addinstance mod/uckkarchive:submit mod/uckkarchive:revise mod/uckkarchive:validate mod/uckkarchive:manage mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` ## 7.6 `tool_uckkintegrity` ```text tool/uckkintegrity:view tool/uckkintegrity:viewall tool/uckkintegrity:opencase tool/uckkintegrity:review tool/uckkintegrity:decide tool/uckkintegrity:appeal tool/uckkintegrity:manage tool/uckkintegrity:export ``` ## 7.7 `report_uckk` ```text report/uckk:view report/uckk:viewown report/uckk:viewall report/uckk:export ``` ## 7.8 `format_uckk` ```text format/uckk:viewmap format/uckk:editmap format/uckk:managepathways ``` ## 7.9 `theme_uckk` ```text theme/uckk:configure theme/uckk:viewdebug ``` ## 7.10 `aiprovider_uckk` ```text aiprovider/uckk:use aiprovider/uckk:configure aiprovider/uckk:viewlogs ``` --- # 8. Cross-preset dependencies Dependencies are divided into **hard storage dependencies** and **soft semantic references**. Hard dependencies must be available before apply writes the target record. Soft references may be checked against JSON presets before the referenced Moodle object exists. | Preset | Hard dependencies | Soft references allowed | | --------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------- | | `categories` | none | none | | `programs` | `categories` when `category` / `category_idnumber` is present | none | | `cohorts` | Moodle cohort API; `categories` for category-context cohorts | none | | `roles` | plugin capabilities declared in `db/access.php` | none | | `capabilities` | `roles`, plugin capabilities declared in `db/access.php` | none | | `competencies` | Moodle core competency API | framework/parent ids inside the same preset | | `course_templates` | activity components when activities are declared | none | | `challenge_templates` | `mod_uckkchallenge` | badges, competencies, roles by stable reference | | `assembly_templates` | `mod_uckkassembly` | roles, cohorts, pathways by stable reference | | `archive_templates` | `mod_uckkarchive` | roles, cohorts, pathways by stable reference | | `courses` | `categories`, `course_templates` when a template is referenced | competencies, badges, programs/pathways by stable reference | | `badges` | Moodle badge API; Moodle badge table columns actually present in the installed schema | programs, pathways, courses, competencies by stable reference | | `pathways` | `programs` | courses, competencies, badges by stable reference | | `reports` | `report_uckk`, report capabilities | none | This split removes the circular hard dependency between `badges` and `pathways`. A badge may describe a pathway-completion badge before the pathway DB row exists, and a pathway may list badge references before the badge DB row exists, as long as both references use stable JSON identifiers and validation can resolve them from preset files. --- # 9. Final implementation alignment requirements To make this reference executable as the final version, `tool_uckkseed` must maintain these alignments: 1. Keep `PRESET_PROGRAMS = 'programs'` routed to `program_seed`. 2. Keep `PRESET_PATHWAYS = 'pathways'` routed to `pathway_seed`. 3. Keep `program_seed` writing to `local_uckk_program`. 4. Keep `pathway_seed` writing to `local_uckk_pathway`. 5. Keep `capability_seed` routed for `capabilities`; do not route capabilities through `role_seed`. 6. Keep `course_template_seed`, `challenge_template_seed`, `assembly_template_seed`, and `archive_template_seed` routed for their template presets. 7. Do not route template presets to `course_seed`. 8. Ensure CLI and form entry points expose the same preset registry as `seeder.php`, including `programs` and `pathways`. 9. Ensure `validate`, dry run, apply, reset, and export use the same preset ids and handlers. 10. Ensure `competency_seed` idnumber validation accepts `^UCKK-COMP-[A-Z0-9-]+$`. 11. Ensure `course_seed` accepts `category` as canonical and may derive it from `category_idnumber` during item normalization. 12. Ensure `category_seed` accepts `parent` as canonical and may derive it from `parent_idnumber` during item normalization. 13. Ensure `badge_seed` supports final program/pathway completion badge fields in addition to symbolic legacy badge fields. 14. Ensure `badge_seed` does not require non-core Moodle badge columns such as `badge.uniquehash`. Optional columns may be used only after checking the installed schema. 15. Keep `reports.json` using top-level `capability`; do not move report capability exclusively into metadata. 16. Ensure generated export payloads use the runtime envelope from this reference. --- # 10. Validation checklist Before committing any `academic_registry_json/*.json` change: ```text [ ] Top-level envelope is schema/component/preset/version/items. [ ] preset matches filename without .json. [ ] items is an array. [ ] Every item has the required stable key for its preset. [ ] All idempotency keys are unique in the preset. [ ] All hard cross-preset dependencies resolve. [ ] Soft cross-preset references resolve either from Moodle storage or from another governed JSON preset. [ ] All capabilities exist in plugin db/access.php or Moodle core. [ ] All Moodle category references resolve through categories.idnumber. [ ] No symbolic UCKK identity is created as a Moodle role. [ ] Program/pathway objects are seedable, not canon-only. [ ] Templates are validated by template seeders, not course_seed. [ ] Badge seed logic does not require non-core Moodle badge columns. [ ] AI metadata is non-authoritative. [ ] Public status notices avoid accreditation confusion. [ ] Standalone mode does not require Konnaxion. ``` Run: ```bash cd C:\mycode\UCKK\moodle\moodle php admin\cli\purge_caches.php php admin\cli\upgrade.php --non-interactive cd C:\mycode\UCKK\moodle\moodle\public php admin\tool\uckkseed\cli\validate.php --presetpath=academic_registry_json ``` --- # 11. Migration note from the older canon document The older document `docs/JSON preset format for UCKK academic registry.txt` described a canonical envelope using: ```json { "schema_version": "1.0", "preset_type": "courses", "source_family": "UCKK canon", "items": [] } ``` That structure is no longer the active runtime seed envelope. It remains useful as historical/conceptual documentation, but the final seedable JSON contract is this reference: ```json { "schema": "uckkseed.preset.v1", "component": "tool_uckkseed", "preset": "courses", "version": 2026051200, "items": [] } ``` Do not keep both formats as peer runtime standards. If canon fields are needed, preserve them inside `metadata` or as item-level domain fields. --- # 12. Source basis This reference is aligned to the repository snapshots dated `2026-05-19T11:04:28` and `2026-05-20T09:03:31`, especially: ```text admin/tool/uckkseed/classes/local/seeder.php admin/tool/uckkseed/classes/local/category_seed.php admin/tool/uckkseed/classes/local/program_seed.php admin/tool/uckkseed/classes/local/pathway_seed.php admin/tool/uckkseed/classes/local/course_seed.php admin/tool/uckkseed/classes/local/cohort_seed.php admin/tool/uckkseed/classes/local/role_seed.php admin/tool/uckkseed/classes/local/competency_seed.php admin/tool/uckkseed/classes/local/badge_seed.php admin/tool/uckkseed/classes/local/report_seed.php admin/tool/uckkseed/cli/seed.php admin/tool/uckkseed/cli/reset.php admin/tool/uckkseed/cli/export_preset.php admin/tool/uckkseed/classes/form/seed_form.php admin/tool/uckkseed/classes/form/reset_form.php local/uckk/db/install.xml local/uckk/classes/local/program.php local/uckk/classes/local/pathway.php all plugin db/access.php files listed above academic_registry_json/*.json docs/JSON preset format for UCKK academic registry.txt ``` ================================================================================================ FILE: docs/README_import_uckkarchive_media.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 0ec3b13eb2f72907458ebf5d8a406151b855603ece3f7d58c18d9f27991c7053 CONTENT_BYTES: 3391 ================================================================================================ # Import UCKK Archive Media Inventory — paquet v2 Ce paquet remplace la première proposition qui ajoutait un fichier sous `mod/uckkarchive/cli/`. La nouvelle structure garde l’import comme outil d’opération : ```text tools/uckk-ops/import/Import-UckkArchiveMedia.ps1 tools/uckk-ops/import/import_uckkarchive_media.php ``` Aucun fichier n’est ajouté dans `mod/uckkarchive/cli/`. ## Principe `Import-UckkArchiveMedia.ps1` fait le prévol : ```text - validation de uckk_inventory.json - résolution des originaux depuis un dossier non public - vérification des extensions supportées - rapport JSON de prévol - appel du bootstrapper PHP Moodle ``` `import_uckkarchive_media.php` charge Moodle avec `config.php`, puis écrit via : ```text - $DB pour les tables uckkarchive_media, uckkarchive_media_version, source, tags, advisories, relations - Moodle File API pour les originaux ``` Les originaux ne sont pas copiés dans `public/`. Ils sont stockés par Moodle File API, typiquement : ```text component = mod_uckkarchive filearea = media_original itemid = uckkarchive_media_version.id filepath = / filename = proposed_filename ``` ## Installation dans le runtime Moodle Depuis la racine Moodle runtime, créer le dossier : ```powershell New-Item -ItemType Directory -Force ` -Path C:\mycode\UCKK\moodle\moodle\public\tools\uckk-ops\import ``` Copier les deux fichiers : ```powershell Copy-Item .\tools\uckk-ops\import\Import-UckkArchiveMedia.ps1 ` C:\mycode\UCKK\moodle\moodle\public\tools\uckk-ops\import\Import-UckkArchiveMedia.ps1 -Force Copy-Item .\tools\uckk-ops\import\import_uckkarchive_media.php ` C:\mycode\UCKK\moodle\moodle\public\tools\uckk-ops\import\import_uckkarchive_media.php -Force ``` ## Dry-run ```powershell pwsh -NoProfile -ExecutionPolicy Bypass -File ` C:\mycode\UCKK\moodle\moodle\public\tools\uckk-ops\import\Import-UckkArchiveMedia.ps1 ` -MoodleRoot "C:\mycode\UCKK\moodle\moodle\public" ` -InventoryPath "C:\mycode\UCKK\uckk-import\uckkarchive\uckk_inventory.json" ` -OriginalsDir "C:\mycode\UCKK\uckk-import\uckkarchive\originals" ` -CmId 42 ` -Mode DryRun ``` ## Apply ```powershell pwsh -NoProfile -ExecutionPolicy Bypass -File ` C:\mycode\UCKK\moodle\moodle\public\tools\uckk-ops\import\Import-UckkArchiveMedia.ps1 ` -MoodleRoot "C:\mycode\UCKK\moodle\moodle\public" ` -InventoryPath "C:\mycode\UCKK\uckk-import\uckkarchive\uckk_inventory.json" ` -OriginalsDir "C:\mycode\UCKK\uckk-import\uckkarchive\originals" ` -CmId 42 ` -Mode Apply ``` ## Paramètres utiles ```text -CmId recommandé : résout le contexte module Moodle -ArchiveId alternative si l’instance est connue -UserId force createdby/modifiedby -AllowMissingFiles permet un import partiel de métadonnées pendant le prévol -UpdateMetadata met à jour les métadonnées si le média existe déjà -ForceNewVersion force une nouvelle version même si le SHA-256 existe déjà -Offset / -Limit import par lot ``` ## Notes de compatibilité Le PHP filtre dynamiquement les champs selon les colonnes réellement présentes dans la DB Moodle. Il supporte donc les noms historiques et les noms du schéma courant quand c’est possible, sans écrire de colonnes absentes. Formats supportés par défaut : ```text .docx .pdf ``` Le `.doc` legacy n’est pas activé par défaut. ================================================================================================ FILE: docs/refactor_public_pages_contract.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: bb91672b06678ff940de388dcdfe47f8c7cb1097888fb2cf2feeef9f40579b8c CONTENT_BYTES: 41535 ================================================================================================ # Refactor public pages — contrat d’exécution **Projet :** UCKK-Moodle **Composant Moodle :** `local_uckk` **Portée :** pages publiques institutionnelles `local/uckk` **Règle de travail :** documentation d’abord, puis code fichier par fichier. **Statut :** contrat à valider avant modification du code. --- ## 1. Objectif Refactoriser les pages publiques UCKK sans changer leur responsabilité fonctionnelle : ```text État actuel - contrôleurs publics minces ; - un registre central lourd : classes/local/public_pages.php ; - un template public_page.mustache trop large ; - certains blocs spécialisés, surtout Médiathèque, déjà séparés partiellement. État cible - un contrat de variables fixe ; - un shell Mustache public minimal ; - des partials Mustache réutilisables ; - une définition PHP par page publique ; - un registre central réduit à un routeur/agrégateur ; - zéro décision métier dans les templates ; - zéro HTML lourd dans les contrôleurs publics. ``` Le refactor doit améliorer la maintenabilité, pas réécrire le produit. --- ## 2. Hors-scope Ce refactor ne doit pas : ```text - changer le modèle de données ; - ajouter de nouvelles tables ; - modifier les permissions Moodle ; - modifier les rôles ; - décider les droits d’accès aux médias ; - exposer des données privées ; - changer les règles d’intégrité ; - créer une nouvelle API AJAX ; - déplacer la logique média de mod_uckkarchive vers local_uckk ; - transformer les reconnaissances UCKK en diplômes publics accrédités ; - centrer les pages publiques sur les limites légales de diplôme, d’accréditation ou de reconnaissance externe ; - présenter une offre de certification comme objectif à court terme ; - refaire tout styles.css ; - refactoriser canon.php, pathways.php ou les pages admin. ``` --- ## 2.1 Contrat éditorial des pages publiques Les pages publiques UCKK doivent présenter l’Univers-Cité King Klown comme une bibliothèque publique vivante, un cadre d’apprentissage ouvert et un espace de diffusion du savoir. Orientation principale : ```text - diffusion immédiate du savoir ; - bibliothèque publique ouverte ; - cadre d’apprentissage familier, modernisé ; - parcours de lecture, de pratique et d’orientation ; - accès public aux repères, cours, archives, médiathèque, assemblées et défis ; - aucune logique de paywall pour accéder au savoir public. ``` Orientation à éviter : ```text - présenter UCKK comme une offre de diplôme ; - centrer les pages sur les limites légales d’accréditation ; - répéter les notices de non-certification sur chaque bloc ; - donner l’impression qu’une certification est un objectif à court terme ; - transformer les Parchemins, niveaux ou titres symboliques en promesses de reconnaissance externe ; - présenter une Voie comme un pipeline Atlas/Moodle plutôt que comme une porte d’entrée vers le savoir ; - exposer au public les détails de préfixes techniques, de projection JSON, de sync ou de source interne. ``` Formulation canonique à utiliser une seule fois lorsque nécessaire : ```text Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future. ``` Règles de rédaction : ```text - dire la limite de reconnaissance une seule fois par surface publique majeure ; - ne pas répéter “diplôme public accrédité”, “statut universitaire public accrédité” ou équivalents dans les FAQ, notices, sections et garde-fous ; - remplacer les formulations défensives par des formulations positives centrées sur l’accès au savoir ; - parler de Voies, parcours, cours publics, bibliothèque, archives, médiathèque, défis, assemblées et apprentissage ouvert ; - ne pas présenter une absence de certification comme le sujet principal des pages ; - écrire les sections de cours comme des portes d’accès : “Explorer les cours publics”, “Accéder aux cours”, “Ouvrir les cours disponibles” ; - garder les champs techniques dans les sources JSON, mais ne pas les transformer en prose publique. ``` Phrase de positionnement recommandée : ```text UCKK n’est pas d’abord un système de certification. C’est une bibliothèque publique vivante et un campus ouvert pour diffuser, organiser et pratiquer le savoir dans un cadre d’apprentissage familier, modernisé et accessible. ``` Convention éditoriale IA : ```text L’ancienne appellation publique “IA gouvernable” est remplacée par “Voie de la Production augmentée par l’IA”. Nom court recommandé : “Production IA”. Nom court éditorial possible : “Production augmentée”. Titre symbolique : “Maître d’œuvre augmenté”. Domaine public : “Production outillée”. ``` Règle de compatibilité technique : ```text Les identifiants techniques existants restent stables tant que la migration complète n’est pas explicitement décidée : faculty_ia_gouvernable voie_ia_gouvernable ia-gouvernable voie_ia_gouvernable.json UCKK-IA IA-HUB ``` Règle de cadrage IA : ```text kOA ne donne pas le contrôle à l’IA. La Voie Production augmentée par l’IA enseigne l’usage productif de l’IA comme atelier de construction : écrire, coder, documenter, concevoir, prototyper, illustrer, organiser, vérifier et accompagner. L’IA est un outil de production, pas une autorité, pas un décideur et pas une instance de gouvernance. ``` --- ## 3. Principe d’exécution Aucune modification massive. ```text 1. Un fichier est modifié ou créé. 2. Le fichier est relu contre ce contrat. 3. La validation minimale du fichier est faite. 4. Seulement ensuite, on passe au fichier suivant. ``` Si un fichier crée une ambiguïté de variable, on arrête le codage et on met d’abord ce contrat à jour. --- ## 4. Variables globales fixes | Variable | Valeur fixe | | ------------------------------ | ---------------------------------------------- | | `COMPONENT` | `local_uckk` | | `PLUGIN_ROOT` | `local/uckk` | | `PUBLIC_ROUTE_ROOT` | `/local/uckk/` | | `PUBLIC_PAGE_REGISTRY_CLASS` | `local_uckk\local\public_pages` | | `PUBLIC_PAGE_RENDERABLE_CLASS` | `local_uckk\output\public_page` | | `PUBLIC_PAGE_TEMPLATE` | `local_uckk/public_page` | | `PUBLIC_PAGE_LAYOUT` | `local_uckk_public` | | `PUBLIC_CSS` | `/local/uckk/styles.css` | | `PUBLIC_PAGE_TYPE` | `public` | | `PUBLIC_IS_PUBLIC` | `true` | | `DESIGN_VERSION` | `2026-layout-v2` | | `FONT_STRATEGY` | `libre-baskerville-primary-eb-garamond-accent` | --- ## 5. Slugs publics fixes ### 5.1 Slugs gérés par le shell public dans ce refactor ```text home about programs courses challenges assemblies integrity archives mediatheque news contact ``` ### 5.2 Route existante hors lot principal ```text campus ``` `campus.php` existe dans `local/uckk`, mais son rendu actuel ne passe pas par `local_uckk\local\public_pages` et `local_uckk\output\public_page`. Il ne doit pas être migré dans le même lot que les pages publiques ci-dessus sauf décision explicite. Variable de statut : ```text CAMPUS_PUBLIC_REFACTOR_STATUS = out_of_scope_batch_1 ``` --- ## 6. Routes publiques fixes | Slug | Route | Contrôleur | | ------------- | ----------------------------- | ----------------- | | `home` | `/local/uckk/index.php` | `index.php` | | `about` | `/local/uckk/about.php` | `about.php` | | `programs` | `/local/uckk/programs.php` | `programs.php` | | `courses` | `/local/uckk/courses.php` | `courses.php` | | `challenges` | `/local/uckk/challenges.php` | `challenges.php` | | `assemblies` | `/local/uckk/assemblies.php` | `assemblies.php` | | `integrity` | `/local/uckk/integrity.php` | `integrity.php` | | `archives` | `/local/uckk/archives.php` | `archives.php` | | `mediatheque` | `/local/uckk/mediatheque.php` | `mediatheque.php` | | `news` | `/local/uckk/news.php` | `news.php` | | `contact` | `/local/uckk/contact.php` | `contact.php` | --- ## 7. Contrat des contrôleurs publics Tous les contrôleurs publics du lot principal doivent rester minces. Forme cible générale : ```php $context = context_system::instance(); $slug = 'about'; \local_uckk\local\public_pages::setup_page($slug, $context); $definition = \local_uckk\local\public_pages::definition($slug); echo $OUTPUT->header(); echo $OUTPUT->render(new \local_uckk\output\public_page($slug, $definition)); echo $OUTPUT->footer(); ``` Règles : ```text - pas de contenu institutionnel dans les contrôleurs ; - pas de HTML direct ; - pas de classes CSS locales construites à la main ; - pas de navigation locale dupliquée ; - pas de logique d’archives, de rôles, de badges, d’intégrité ou d’inscription ; - exception contrôlée : mediatheque.php peut lire les paramètres URL et préparer l’état initial AMD. ``` --- ## 8. Exception contrôlée : `mediatheque.php` `mediatheque.php` reste un contrôleur mince, mais il possède des paramètres publics nécessaires à l’explorateur. Variables autorisées dans `mediatheque.php` : ```text cmid archiveid q type mediatype collection tag source advisory cultural audience lang validation sort page perpage item ``` État initial AMD autorisé : ```text rootId service cmid archiveid query filters page perpage sort sitewide ``` Service AJAX fixe : ```text MEDIATHEQUE_SEARCH_SERVICE = mod_uckkarchive_search_mediatheque ``` Règles : ```text - local_uckk affiche la surface publique ; - mod_uckkarchive reste propriétaire des médias, droits, avis de contenu, protocoles culturels et filtres d’accès ; - mediatheque.php ne doit pas interroger directement les tables média ; - mediatheque.php peut passer des overrides à public_page : - mediatheque_explorer_id - mediatheque_initial_state - has_mediatheque_explorer ``` --- ## 9. Classes PHP finales ### 9.1 Classe registre conservée ```text classes/local/public_pages.php ``` Classe : ```php namespace local_uckk\local; final class public_pages ``` Responsabilités finales : ```text - nettoyer le slug ; - configurer PAGE ; - configurer le breadcrumb ; - résoudre le titre de page ; - fournir la navigation commune ; - appeler la classe de définition correspondant au slug ; - fusionner la base commune et la définition de page ; - ne plus contenir le contenu complet de toutes les pages. ``` Méthodes publiques conservées : ```php public static function setup_page(string $slug, ?context $context = null): void; public static function definition(string $slug): array; ``` Méthodes internes autorisées : ```php private static function base_definition(string $slug): array; private static function page_definition(string $slug): array; private static function default_navigation(): array; private static function merge_definition(array $base, array $overrides): array; private static function clean_slug(string $slug): string; private static function script_for_slug(string $slug): string; private static function page_title(string $slug): string; private static function site_heading(): string; private static function string_or_fallback(string $identifier, string $fallback): string; ``` ### 9.2 Classes de définition par page Dossier cible : ```text classes/local/public_pages/ ``` Namespace cible : ```php namespace local_uckk\local\public_pages; ``` Convention de méthode : ```php public static function definition(): array; ``` Fichiers à créer : ```text classes/local/public_pages/home.php classes/local/public_pages/about.php classes/local/public_pages/programs.php classes/local/public_pages/courses.php classes/local/public_pages/challenges.php classes/local/public_pages/assemblies.php classes/local/public_pages/integrity.php classes/local/public_pages/archives.php classes/local/public_pages/mediatheque.php classes/local/public_pages/news.php classes/local/public_pages/contact.php ``` Classes à créer : ```php local_uckk\local\public_pages\home local_uckk\local\public_pages\about local_uckk\local\public_pages\programs local_uckk\local\public_pages\courses local_uckk\local\public_pages\challenges local_uckk\local\public_pages\assemblies local_uckk\local\public_pages\integrity local_uckk\local\public_pages\archives local_uckk\local\public_pages\mediatheque local_uckk\local\public_pages\news local_uckk\local\public_pages\contact ``` Chaque classe de page : ```text - retourne un tableau de définition ; - ne rend aucun HTML ; - ne connaît pas $OUTPUT ; - ne configure pas $PAGE ; - ne fait pas de redirect ; - ne modifie pas la base de données ; - ne lit pas les paramètres HTTP, sauf décision documentée séparément. ``` --- ## 10. Cas particulier : `programs` La page `programs` utilise actuellement des cartes dynamiques depuis le registre Moodle UCKK des programmes actifs. Responsabilité cible : ```text classes/local/public_pages/programs.php ``` Cette classe peut contenir : ```php public static function definition(): array; private static function with_program_cards(array $definition): array; private static function program_cards(string $status): array; private static function program_type_label(string $programtype): string; private static function clean_modifier($modifier): string; ``` Règles : ```text - public_pages.php ne doit plus contenir la requête SQL des programmes actifs ; - les cartes dynamiques restent limitées à programs ; - si la table local_uckk_program n’existe pas, la page doit continuer à fonctionner ; - les programmes non actifs ne sont pas affichés publiquement ; - aucune donnée privée n’est exposée. ``` --- ## 11. Classe de rendu conservée Fichier : ```text classes/output/public_page.php ``` Classe : ```php namespace local_uckk\output; final class public_page implements renderable, templatable ``` Responsabilités : ```text - recevoir slug + définition ; - normaliser les anciennes clés si nécessaire ; - exporter un objet stdClass pour Mustache ; - générer les flags booléens ; - générer les classes CSS ; - ne pas décider le contenu institutionnel ; - ne pas interroger la base de données ; - ne pas rendre de HTML. ``` Template fixe retourné : ```php private const TEMPLATE = 'local_uckk/public_page'; ``` --- ## 12. Templates Mustache finaux ### 12.1 Shell principal ```text templates/public_page.mustache ``` Nom Moodle : ```text local_uckk/public_page ``` Responsabilité : ```text - contenir le conteneur racine ; - appeler les partials ; - ne contenir aucune boucle longue ; - ne contenir aucun bloc spécialisé lourd ; - ne pas contenir de logique métier. ``` Forme cible : ```mustache
{{#hasnavigation}} {{> local_uckk/public/nav }} {{/hasnavigation}} {{> local_uckk/public/hero }} {{#hasquicklinks}} {{> local_uckk/public/quicklinks }} {{/hasquicklinks}}
{{#hassections}} {{> local_uckk/public/sections }} {{/hassections}} {{#has_home_feature}} {{> local_uckk/pages/home_feature }} {{/has_home_feature}} {{#has_mediatheque_explorer}} {{> local_uckk/pages/mediatheque_explorer }} {{/has_mediatheque_explorer}} {{#hascards}} {{> local_uckk/public/cards }} {{/hascards}}
{{#hasaside}} {{> local_uckk/public/aside }} {{/hasaside}}
``` ### 12.2 Partials publics communs Dossier : ```text templates/public/ ``` | Fichier | Nom Moodle | Responsabilité | | ------------------------ | --------------------------------- | ------------------------------------------------------------ | | `nav.mustache` | `local_uckk/public/nav` | Navigation publique | | `hero.mustache` | `local_uckk/public/hero` | Eyebrow, titre, sous-titre, résumé, boundary notice si rendu | | `quicklinks.mustache` | `local_uckk/public/quicklinks` | Repères rapides | | `sections.mustache` | `local_uckk/public/sections` | Boucle des sections de page | | `cards.mustache` | `local_uckk/public/cards` | Cartes de page génériques | | `aside.mustache` | `local_uckk/public/aside` | Colonne latérale ; rend uniquement metadata et CTA | | `metadata.mustache` | `local_uckk/public/metadata` | Liste metadata | | `cta.mustache` | `local_uckk/public/cta` | Bloc CTA | | `prompt_groups.mustache` | `local_uckk/public/prompt_groups` | Groupes d’invites réutilisables | Note contractuelle : `notices` et `hasnotices` existent dans le contexte exporté par `public_page.php`, mais l’état courant documenté ne crée pas de partial `public/notices.mustache` et ne rend pas les notices dans l’aside. `aside.mustache` rend uniquement les sous-partials `metadata` et `cta`. ### 12.3 Templates spécialisés par page Dossier : ```text templates/pages/ ``` | Fichier | Nom Moodle | Responsabilité | | ------------------------------- | --------------------------------------- | ---------------------------------- | | `home_feature.mustache` | `local_uckk/pages/home_feature` | Bloc spécifique Accueil, si activé | | `mediatheque_explorer.mustache` | `local_uckk/pages/mediatheque_explorer` | Explorateur Médiathèque public | Migration : ```text Ancien : templates/mediatheque_explorer.mustache Ancien nom : local_uckk/mediatheque_explorer Nouveau : templates/pages/mediatheque_explorer.mustache Nouveau nom : local_uckk/pages/mediatheque_explorer ``` --- ## 13. Contrat de contexte Mustache racine Clés racine autorisées dans `public_page.mustache` : ```text uniqid slug component pagetype ispublic layout navigationlayout classes rootclasses layoutclasses shellclasses bodyclasses mainclasses asideclasses railclasses headerclasses heroclasses contentclasses asideinnerclasses typographyclasses sectiongridclasses cardgridclasses designversion fontstrategy eyebrow title subtitle summary boundarynotice haseyebrow hassubtitle hassummary hasboundarynotice navigation hasnavigation navigationclasses quicklinks hasquicklinks sections hassections cards hascards cardsheading notices hasnotices metadata hasmetadata cta hascta hasaside has_home_feature home_feature has_mediatheque_explorer mediatheque_explorer_id mediatheque_initial_state mediatheque_initial_state_json ``` Règle : tout nouveau champ Mustache doit être ajouté ici avant d’être codé. --- ## 14. Flags booléens autorisés ```text ispublic haseyebrow hassubtitle hassummary hasboundarynotice hasnavigation hasquicklinks hassections hascards hasnotices hasmetadata hascta hasaside has_home_feature has_mediatheque_explorer haspromptgroups hasitems hasaction hasariacurrent active ``` Règles : ```text - les flags sont calculés par public_page.php ; - les templates ne déduisent pas les flags ; - une section Mustache doit utiliser un flag clair si le champ peut être vide ; - pas de nouveau préfixe aléatoire comme is_, show_, enable_ sans mise à jour de ce contrat. ``` --- ## 15. Contrat des tableaux exportés ### 15.1 `navigation[]` ```text key label url active classes itemclasses ariacurrent hasariacurrent ``` ### 15.2 `quicklinks[]` ```text label description url classes ``` ### 15.3 `sections[]` ```text type eyebrow title body items cards classes hasitems ``` `sections[].items[]` autorise : ```text eyebrow title body url actionlabel classes hasaction ``` ### 15.4 `cards[]` ```text eyebrow title body url actionlabel type classes hasaction ``` ### 15.5 `notices[]` — exporté, non rendu dans l’état courant ```text title body type classes hastitle ``` Types autorisés : ```text institutional integrity warning light ``` Règle de rendu : dans l’état courant, aucune partial `templates/public/notices.mustache` n’est créée et aucune inclusion `local_uckk/public/notices` n’est attendue. Les notices restent dans le contrat de données pour compatibilité avec `public_page.php`, mais leur non-rendu est intentionnellement documenté. Règle éditoriale : les notices ne doivent pas servir à répéter partout les limites d’accréditation. Si une notice institutionnelle est rendue publiquement, elle doit privilégier la mission d’ouverture, de transmission et de diffusion du savoir. La limite de reconnaissance doit rester condensée dans la formule canonique unique. ### 15.6 `metadata[]` ```text label value ``` ### 15.7 `cta` ```text title body url label actionlabel classes ``` ### 15.8 `promptgroups[]` ```text eyebrow title body items classes ``` `promptgroups[].items[]` autorise : ```text title body url label classes ``` --- ## 16. Valeurs fixes de layout Layouts autorisés : ```text standard wide full ``` Navigation layouts autorisés : ```text singleline wrap ``` Typography values autorisées : ```text institutional editorial display ``` Visual style documenté : ```text civic-encyclopedic-retrofuturism ``` --- ## 17. Règles CSS Fichier CSS unique conservé : ```text styles.css ``` Pas de fichier CSS par page. Préfixes autorisés : ```text local-uckk- local-uckk-public- local-uckk-public-nav- local-uckk-public-hero- local-uckk-public-section- local-uckk-public-card- local-uckk-public-aside- local-uckk-public-meta- local-uckk-public-cta- local-uckk-public-prompt- local-uckk-home- local-uckk-mediatheque- ``` Organisation cible dans `styles.css` : ```css /* Public shell */ /* Public nav */ /* Public hero */ /* Public quicklinks */ /* Public sections */ /* Public cards */ /* Public aside */ /* Public metadata */ /* Public CTA */ /* Public prompt groups */ /* Page: home */ /* Page: mediatheque */ /* Responsive */ ``` Règles : ```text - ne pas renommer massivement les classes existantes pendant le split Mustache ; - d’abord préserver le HTML rendu ; - ensuite seulement nettoyer le CSS ; - aucune classe Bootstrap nouvelle sans justification ; - aucun style inline. ``` --- ## 18. Règles de langue Fichiers de langue existants : ```text lang/fr/local_uckk.php lang/en/local_uckk.php ``` Règles : ```text - ne pas ajouter de chaîne tant qu’un texte reste strictement interne au template et déjà existant ; - ajouter une chaîne si un nouveau libellé devient réutilisable ; - ajouter les clés en français et en anglais dans le même changement ; - ne pas mélanger les changements de langue avec le découpage PHP sauf nécessité. ``` Clés candidates si externalisation décidée : ```text public_quicklinks_heading public_metadata_heading public_aside_aria_label public_cta_default_label public_navigation_aria_label ``` --- ## 19. AMD et Médiathèque Fichier AMD conservé : ```text amd/src/mediatheque_explorer.js ``` Module AMD fixe : ```text local_uckk/mediatheque_explorer ``` Appel autorisé : ```php $PAGE->requires->js_call_amd('local_uckk/mediatheque_explorer', 'init', [$initialstate]); ``` Règles : ```text - ne pas renommer le module AMD dans ce refactor ; - ne pas changer le contrat de service AJAX ; - ne pas déplacer la recherche côté PHP local_uckk ; - le template spécialisé affiche seulement le conteneur et l’état initial. ``` --- ## 20. Arborescence cible ```text local/uckk/ ├── index.php ├── about.php ├── programs.php ├── courses.php ├── challenges.php ├── assemblies.php ├── integrity.php ├── archives.php ├── mediatheque.php ├── news.php ├── contact.php ├── campus.php # hors lot principal │ ├── classes/ │ ├── local/ │ │ ├── public_pages.php │ │ └── public_pages/ │ │ ├── home.php │ │ ├── about.php │ │ ├── programs.php │ │ ├── courses.php │ │ ├── challenges.php │ │ ├── assemblies.php │ │ ├── integrity.php │ │ ├── archives.php │ │ ├── mediatheque.php │ │ ├── news.php │ │ └── contact.php │ │ │ └── output/ │ └── public_page.php │ ├── templates/ │ ├── public_page.mustache │ │ │ ├── public/ │ │ ├── nav.mustache │ │ ├── hero.mustache │ │ ├── quicklinks.mustache │ │ ├── sections.mustache │ │ ├── cards.mustache │ │ ├── aside.mustache │ │ ├── metadata.mustache │ │ ├── cta.mustache │ │ └── prompt_groups.mustache │ │ │ ├── pages/ │ │ ├── home_feature.mustache │ │ └── mediatheque_explorer.mustache │ │ │ ├── program_card.mustache │ └── public_prompt_groups.mustache # à supprimer ou laisser comme compat temporaire selon usage réel │ ├── styles.css └── amd/ └── src/ └── mediatheque_explorer.js ``` --- ## 21. Fichiers à créer ```text docs/refactor_public_pages_contract.md templates/public/nav.mustache templates/public/hero.mustache templates/public/quicklinks.mustache templates/public/sections.mustache templates/public/cards.mustache templates/public/aside.mustache templates/public/metadata.mustache templates/public/cta.mustache templates/public/prompt_groups.mustache templates/pages/home_feature.mustache templates/pages/mediatheque_explorer.mustache classes/local/public_pages/home.php classes/local/public_pages/about.php classes/local/public_pages/programs.php classes/local/public_pages/courses.php classes/local/public_pages/challenges.php classes/local/public_pages/assemblies.php classes/local/public_pages/integrity.php classes/local/public_pages/archives.php classes/local/public_pages/mediatheque.php classes/local/public_pages/news.php classes/local/public_pages/contact.php ``` --- ## 22. Fichiers à modifier ```text templates/public_page.mustache classes/local/public_pages.php classes/output/public_page.php mediatheque.php styles.css lang/fr/local_uckk.php # seulement si nouvelles chaînes lang/en/local_uckk.php # seulement si nouvelles chaînes classes/local/faculty/faculty_normalizer.php classes/local/faculty/faculty_page_builder.php classes/local/faculty/faculty_validator.php content/faculties/architecture-sociotechnique.faculty.json content/faculties/ecologie.faculty.json content/faculties/economie.faculty.json content/faculties/ecosysteme-digital-koa.faculty.json content/faculties/grand-jeu-social.faculty.json content/faculties/ia-gouvernable.faculty.json content/faculties/intervention-sociale-systemes-humains.faculty.json content/faculties/linguistique-architecture-du-sens.faculty.json content/faculties/metaphysique.faculty.json content/faculties/sciences-politiques.faculty.json content/faculties/faculty_manifest.json # si le nom public ou l’ordre de la Voie IA est exposé atlas/atlas_manifest.json # si le nom public ou le titre de la Voie IA y apparaît atlas/voies/voie_ia_gouvernable.json # à corriger pour remplacer le cadrage public “IA gouvernable” par “Production augmentée par l’IA” academic_registry_json/categories.json # si exposé publiquement academic_registry_json/programs.json # si exposé publiquement academic_registry_json/badges.json # si exposé publiquement academic_registry_json/courses.json # si exposé publiquement academic_registry_json/course_templates.json # si exposé publiquement docs/12_faculty_pages_atlas_public_contract.md # si la convention IA est aussi documentée côté Faculty/Atlas docs/13_faculty_json_authoring_guide.md # si le guide auteur mentionne IA gouvernable docs/14_atlas_moodle_sync_reference.md # si la référence de sync expose le nom public ``` --- ## 23. Fichiers à ne pas modifier dans ce refactor ```text classes/api/* classes/external/* classes/form/* classes/local/program.php classes/local/pathway.php classes/local/canon_item.php classes/local/player_profile.php classes/privacy/provider.php db/* canon.php pathways.php campus.php # sauf lot séparé explicite ``` --- ## 24. Ordre exact de codage fichier par fichier ### Lot 0 — Documentation et sécurité ```text 0.1 Créer docs/refactor_public_pages_contract.md 0.2 git status --short 0.3 git switch -c refactor-public-pages ``` ### Lot 1 — Dossiers ```text 1.1 Créer templates/public/ 1.2 Créer templates/pages/ 1.3 Créer classes/local/public_pages/ ``` ### Lot 2 — Partials Mustache communs Coder un fichier à la fois, en copiant d’abord le HTML existant depuis `public_page.mustache`. ```text 2.1 templates/public/nav.mustache 2.2 templates/public/hero.mustache 2.3 templates/public/quicklinks.mustache 2.4 templates/public/sections.mustache 2.5 templates/public/cards.mustache 2.6 templates/public/metadata.mustache 2.7 templates/public/cta.mustache 2.8 templates/public/aside.mustache 2.9 templates/public/prompt_groups.mustache ``` Validation après chaque fichier Mustache : ```text - vérifier que les variables utilisées existent dans ce contrat ; - vérifier que le partial ne contient pas de variable nouvelle non documentée ; - vérifier que le partial ne contient aucune logique métier ; - vérifier l’indentation Mustache. ``` ### Lot 3 — Partials spécialisés ```text 3.1 templates/pages/mediatheque_explorer.mustache 3.2 templates/pages/home_feature.mustache ``` Règle : `mediatheque_explorer.mustache` doit être déplacé sans changer le contrat AMD. ### Lot 4 — Shell Mustache ```text 4.1 templates/public_page.mustache ``` Règle : le shell devient uniquement un conteneur + appels de partials. Validation : ```text - aucune boucle longue dans le shell ; - aucune carte directement rendue dans le shell ; - aucune metadata directement rendue dans le shell ; - aucune logique Médiathèque directement dans le shell ; - le nom du template reste local_uckk/public_page. ``` ### Lot 5 — Classes de page PHP Créer et valider une classe à la fois : ```text 5.1 classes/local/public_pages/home.php 5.2 classes/local/public_pages/about.php 5.3 classes/local/public_pages/programs.php 5.4 classes/local/public_pages/courses.php 5.5 classes/local/public_pages/challenges.php 5.6 classes/local/public_pages/assemblies.php 5.7 classes/local/public_pages/integrity.php 5.8 classes/local/public_pages/archives.php 5.9 classes/local/public_pages/mediatheque.php 5.10 classes/local/public_pages/news.php 5.11 classes/local/public_pages/contact.php ``` Validation après chaque fichier PHP : ```powershell php -l local\uckk\classes\local\public_pages\home.php ``` Adapter le nom du fichier à chaque étape. ### Lot 6 — Registre central ```text 6.1 classes/local/public_pages.php ``` Objectif : réduire le fichier à un registre/routeur. Validation : ```text - public_pages::setup_page() fonctionne encore ; - public_pages::definition($slug) fonctionne encore ; - clean_slug garde les mêmes slugs autorisés ; - default_navigation garde les mêmes routes ; - la définition de page vient des nouvelles classes ; - la requête SQL programmes n’est plus dans public_pages.php. ``` ### Lot 7 — Exporter de rendu ```text 7.1 classes/output/public_page.php ``` Changements autorisés : ```text - ajouter has_home_feature ; - ajouter home_feature si nécessaire ; - ajouter promptgroups / haspromptgroups si nécessaire ; - préserver les clés existantes ; - préserver TEMPLATE = local_uckk/public_page. ``` Validation : ```powershell php -l local\uckk\classes\output\public_page.php ``` ### Lot 8 — Contrôleur Médiathèque ```text 8.1 mediatheque.php ``` Objectif : vérifier que le contrôleur passe seulement les overrides nécessaires et que le template spécialisé utilisé est le nouveau partial `local_uckk/pages/mediatheque_explorer` via le shell. Validation : ```text - URL params conservés ; - initialstate conservé ; - js_call_amd conservé ; - aucun accès direct aux tables média ; - aucun HTML fallback modifié sauf nécessité. ``` ### Lot 8.5 — Refonte éditoriale des contenus publics ```text 8.5.1 Réécrire les définitions textuelles des pages publiques. 8.5.2 Réécrire les profils publics de facultés. 8.5.3 Réduire les mentions d’accréditation à une seule formule canonique. 8.5.4 Vérifier que les pages parlent d’abord de bibliothèque publique, diffusion du savoir et apprentissage ouvert. 8.5.5 Vérifier qu’aucune FAQ ou notice ne transforme la non-certification en thème principal. 8.5.6 Remplacer les formulations publiques de type “projeté depuis l’Atlas”, “dérivé de l’Atlas”, “préfixe Moodle” ou “Espaces Moodle associés” par des formulations orientées visiteur : “Explorer les cours publics”, “Accéder aux cours”, “Ouvrir les cours disponibles”. 8.5.7 Renommer publiquement la Voie IA : “Voie de la Production augmentée par l’IA”, nom court “Production IA”, titre symbolique “Maître d’œuvre augmenté”. 8.5.8 Conserver les identifiants techniques IA existants tant que la migration complète n’est pas décidée : faculty_ia_gouvernable, voie_ia_gouvernable, ia-gouvernable, voie_ia_gouvernable.json, UCKK-IA, IA-HUB. 8.5.9 Recentrer le cadrage IA : l’IA sert à produire, écrire, coder, documenter, concevoir, prototyper, illustrer, vérifier et accompagner; elle ne gouverne pas, ne décide pas et ne reçoit pas l’autorité finale. ``` Formulation publique recommandée pour la Voie IA : ```text La Voie de la Production augmentée par l’IA apprend à utiliser l’intelligence artificielle comme atelier de production : écrire, coder, documenter, concevoir, prototyper, illustrer, organiser, vérifier et accompagner, sans déléguer le jugement humain ni l’autorité finale. ``` ### Lot 9 — CSS et langue ```text 9.1 styles.css 9.2 lang/fr/local_uckk.php si nécessaire 9.3 lang/en/local_uckk.php si nécessaire ``` Règle : CSS en dernier, seulement après stabilisation du HTML. --- ## 25. Commandes de validation locales Depuis le dépôt source : ```powershell cd "C:\mycode\UCKK\uckk-moodle" git status --short git diff --check ``` Lint PHP des fichiers modifiés : ```powershell php -l local\uckk\classes\local\public_pages.php php -l local\uckk\classes\output\public_page.php php -l local\uckk\mediatheque.php php -l local\uckk\index.php php -l local\uckk\about.php php -l local\uckk\programs.php php -l local\uckk\courses.php php -l local\uckk\challenges.php php -l local\uckk\assemblies.php php -l local\uckk\integrity.php php -l local\uckk\archives.php php -l local\uckk\news.php php -l local\uckk\contact.php ``` Synchronisation locale Moodle : ```powershell robocopy ".\local\uckk" "C:\mycode\UCKK\moodle\moodle\public\local\uckk" /MIR /XD ".git" "node_modules" "vendor" cd "C:\mycode\UCKK\moodle\moodle" php admin\cli\purge_caches.php ``` Pages à ouvrir après purge : ```text /local/uckk/index.php /local/uckk/about.php /local/uckk/programs.php /local/uckk/courses.php /local/uckk/challenges.php /local/uckk/assemblies.php /local/uckk/integrity.php /local/uckk/archives.php /local/uckk/mediatheque.php /local/uckk/news.php /local/uckk/contact.php ``` --- ## 26. Critères de non-régression Le refactor est invalide si : ```text - une page publique affiche une erreur Mustache ; - une page publique perd sa navigation ; - mediatheque.php ne lance plus l’AMD ; - programs.php perd les cartes dynamiques actives ; - une page publique expose des données privées ; - public_pages.php contient encore tout le contenu de toutes les pages après le lot 6 ; - public_page.mustache contient encore les gros blocs de rendu après le lot 4 ; - styles.css est réécrit avant stabilisation du HTML ; - campus.php est modifié sans lot séparé ; - une variable Mustache non documentée est ajoutée ; - une page publique répète plusieurs fois les limites de diplôme ou d’accréditation ; - une page donne l’impression qu’une certification est prévue à court terme ; - une page présente le savoir public comme contenu derrière paywall ; - une page parle davantage de non-accréditation que de diffusion du savoir. ``` --- ## 27. Critères de fin Le refactor est terminé quand : ```text - docs/refactor_public_pages_contract.md existe ; - public_page.mustache est un shell ; - templates/public/*.mustache contient les blocs communs ; - templates/pages/*.mustache contient les blocs spécialisés ; - classes/local/public_pages/*.php contient les définitions par page ; - classes/local/public_pages.php est réduit à un routeur/agrégateur ; - classes/output/public_page.php exporte toutes les variables documentées ; - les 11 pages publiques du lot principal fonctionnent après purge caches ; - les pages publiques présentent UCKK comme bibliothèque publique vivante et cadre d’apprentissage ouvert ; - les limites de reconnaissance sont condensées dans la formule canonique unique lorsque nécessaire ; - git diff --check ne signale rien ; - les fichiers PHP modifiés passent php -l. ``` --- ## 28. Règle de commit Commits recommandés : ```text Commit 1 — Add public page refactor contract Commit 2 — Split public page Mustache into partials Commit 3 — Split public page definitions by slug Commit 4 — Wire public page registry to page definition classes Commit 5 — Finalize public page rendering context and CSS cleanup Commit 6 — Align public editorial content with open knowledge positioning ``` Ne pas mélanger : ```text - split Mustache ; - split PHP ; - nettoyage CSS ; - ajout de contenu ; - refonte éditoriale des facultés ; - migration campus. ``` --- ## 29. Décisions verrouillées ```text DÉCISION 1 Un seul fichier de documentation pilote ce refactor. DÉCISION 2 Le code est modifié fichier par fichier. DÉCISION 3 Le shell public reste local_uckk/public_page. DÉCISION 4 Les pages publiques principales sont au nombre de 11 dans le lot 1. DÉCISION 5 campus.php est hors lot principal. DÉCISION 6 mediatheque.php garde son état initial AMD spécifique. DÉCISION 7 programs possède la seule logique dynamique de cartes dans les définitions publiques. DÉCISION 8 styles.css reste unique. DÉCISION 9 Les notices exportées restent dans le contrat de données, mais l’état courant documente explicitement leur non-rendu : aucun `templates/public/notices.mustache` n’est créé et `aside.mustache` rend seulement `metadata` et `cta`. DÉCISION 10 Toute nouvelle variable doit être ajoutée à ce contrat avant d’être utilisée. DÉCISION 11 Les pages publiques UCKK sont d’abord des surfaces de diffusion du savoir, non des surfaces de certification. DÉCISION 12 La limite de reconnaissance est formulée une seule fois avec la phrase canonique : “Les éventuelles reconnaissances UCKK demeurent internes, sauf reconnaissance officielle future.” DÉCISION 13 Il n’y a pas de projet à court terme d’offrir une certification, un diplôme ou une reconnaissance formelle externe. DÉCISION 14 Le savoir public UCKK ne doit pas être présenté comme un contenu derrière paywall. DÉCISION 15 L’appellation publique de l’ancienne Voie IA gouvernable devient : “Voie de la Production augmentée par l’IA”. Le nom court public recommandé est “Production IA”. Le titre symbolique est “Maître d’œuvre augmenté”. DÉCISION 16 L’IA est présentée comme outil de production et d’augmentation du travail humain. Elle ne doit pas être présentée comme instance de contrôle, autorité finale ou sujet de gouvernance autonome. ``` ================================================================================================ FILE: docs/TODO_refactor_explorateur_cours_public_UCKK.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 3c08e032fe23359a2ba1431cb784d020e876a175cde01951e078d6dd1d52cc42 CONTENT_BYTES: 10589 ================================================================================================ # TODO — Refactor propre de l’explorateur de cours public UCKK ## Objectif Rendre l’explorateur de cours public cohérent, maintenable et centralisé. Le comportement attendu est simple : ```text Même données Même rendu de carte Même statut de page Même résultat visuel avant filtre et après filtre AJAX ``` ## Problèmes à corriger ### 1. Rendu non centralisé des cartes de cours Actuellement, la carte de cours est rendue par deux chemins différents : ```text Avant filtre : PHP → Mustache → course_explorer.mustache Après filtre : AJAX → course_explorer.js → création DOM manuelle ``` Conséquence : un correctif appliqué au rendu initial ne corrige pas forcément le rendu après filtre. ### 2. Statut “Cours affichés” non mis à jour après filtre Le bloc de page : ```text Statut de la page Cours affichés 114 / 114 ``` est généré au chargement initial, mais n’est pas relié proprement à l’explorateur AJAX. Après filtrage, le nombre visible change, mais la metadata de page reste figée. ### 3. Contrat de données trop flou Plusieurs noms existent pour les mêmes concepts : ```text shortname / code category / categorylabel / eyebrow body / summary / description total_label / resultscountlabel / resultsummary ``` Ces synonymes favorisent les divergences entre PHP, Mustache et JavaScript. ### 4. Metadata sans clé stable La metadata de page est actuellement surtout descriptive : ```php [ 'label' => 'Cours affichés', 'value' => '114 / 114', ] ``` Il manque une clé technique stable, par exemple : ```php [ 'key' => 'course_count', 'label' => 'Cours affichés', 'value' => '114 / 114', ] ``` Sans clé stable, le JavaScript devrait cibler du texte visible, ce qui est fragile. ### 5. Contrôleur trop chargé `local/uckk/courses.php` fait trop de choses : ```text - lecture de la requête - lecture des cours Moodle - filtrage - tri - construction des cartes - construction des filtres - construction de la metadata - construction du contexte initial - rendu de la page ``` Le contrôleur devrait seulement lire la requête, appeler un service applicatif, puis rendre la page. --- ## Fichiers à corriger ### Obligatoires ```text local/uckk/courses.php local/uckk/classes/output/public_page.php local/uckk/classes/external/search_public_courses.php local/uckk/templates/public/metadata.mustache local/uckk/templates/pages/course_explorer.mustache local/uckk/amd/src/course_explorer.js ``` ### À créer ```text local/uckk/templates/components/course_card.mustache local/uckk/classes/local/course_explorer.php ``` Nom alternatif acceptable pour la classe : ```text local/uckk/classes/local/public_courses.php ``` ### Optionnel, mais recommandé ```text local/uckk/tests/behat/local_uckk_course_explorer.feature ``` --- ## Contrat de données cible ### Vocabulaire canonique Utiliser ces noms partout où possible : ```text coursecode = code public du cours, ex. UCKK-AS251 pathwaylabel = libellé de voie, ex. 04 — Voie de l’Architecture sociotechnique summary = résumé court du cours visiblecount = nombre de cours affichés après filtres totalcount = nombre total de cours publics statuslabel = texte complet de statut, ex. 14 / 114 courses = liste des cartes de cours hasmore = pagination disponible ``` ### Exemple de réponse AJAX cible ```json { "courses": [], "visiblecount": 14, "totalcount": 114, "statuslabel": "14 / 114", "hasmore": false, "page": 1, "perpage": 12 } ``` ### Exemple de contexte initial cible Le contexte initial PHP doit exposer les mêmes concepts : ```php [ 'courses' => $courses, 'visiblecount' => $visiblecount, 'totalcount' => $totalcount, 'statuslabel' => $visiblecount . ' / ' . $totalcount, 'hasmore' => $hasmore, ] ``` --- ## Plan de refactor ### Étape 1 — Créer un partial unique pour les cartes Créer : ```text local/uckk/templates/components/course_card.mustache ``` Responsabilité unique : rendre une carte de cours. Le partial doit afficher : ```text Titre Résumé Voie sans libellé “Voie” Code sans libellé “Numéro de cours” ``` Rendu attendu : ```text Boucles de rétroaction clinique et apprentissage institutionnel Appliquer les principes de feedback, diagnostic, suivi et apprentissage institutionnel au domaine de la santé. 04 — Voie de l’Architecture sociotechnique UCKK-AS251 ``` ### Étape 2 — Faire utiliser le partial par le rendu initial Modifier : ```text local/uckk/templates/pages/course_explorer.mustache ``` Remplacer le HTML interne de carte par : ```mustache {{> local_uckk/components/course_card }} ``` ### Étape 3 — Faire utiliser le même partial par AJAX Modifier : ```text local/uckk/amd/src/course_explorer.js ``` Remplacer la création DOM manuelle des cartes par le rendu via Moodle templates : ```js import Templates from 'core/templates'; const renderCourseCard = async course => { return Templates.render('local_uckk/components/course_card', course); }; ``` Puis injecter le HTML retourné dans la région résultats. Le JavaScript ne doit plus décider du HTML exact d’une carte. ### Étape 4 — Ajouter une clé stable aux metadata Modifier : ```text local/uckk/courses.php ``` Faire en sorte que la metadata “Cours affichés” contienne une clé stable : ```php [ 'key' => 'course_count', 'label' => 'Cours affichés', 'value' => $visiblecount . ' / ' . $totalcount, ] ``` ### Étape 5 — Exporter la clé metadata Modifier : ```text local/uckk/classes/output/public_page.php ``` S’assurer que l’export metadata conserve : ```text key label value ``` Et ajoute au besoin : ```text region classes ``` Exemple de région : ```text page-metadata-course-count ``` ### Étape 6 — Exposer une région DOM stable Modifier : ```text local/uckk/templates/public/metadata.mustache ``` Pour la metadata avec `key = course_count`, rendre un attribut stable : ```html
{{value}}
``` Éviter de cibler le texte visible “Cours affichés”. ### Étape 7 — Mettre à jour le statut après AJAX Modifier : ```text local/uckk/amd/src/course_explorer.js ``` Après chaque réponse AJAX, mettre à jour : ```text [data-region="course-status"] [data-region="course-count-summary"] ``` Le champ metadata doit recevoir : ```js response.statuslabel ``` ou, en fallback contrôlé : ```js `${response.visiblecount} / ${response.totalcount}` ``` ### Étape 8 — Formaliser le service applicatif Créer : ```text local/uckk/classes/local/course_explorer.php ``` Responsabilités : ```text - lire les cours publics visibles - construire les cartes - filtrer - trier - paginer - produire le contrat initial - produire le contrat AJAX ``` Le contrôleur `courses.php` et le service externe `search_public_courses.php` doivent appeler cette même classe. ### Étape 9 — Alléger le contrôleur Modifier : ```text local/uckk/courses.php ``` Objectif final : ```php $state = course_explorer::request_state(); $context = course_explorer::initial_context($state); $definition = public_pages::definition('courses'); $definition['course_explorer'] = $context; $definition['metadata'] = course_explorer::page_metadata($context); echo $OUTPUT->render(new public_page('courses', $definition)); ``` ### Étape 10 — Aligner le service AJAX Modifier : ```text local/uckk/classes/external/search_public_courses.php ``` Le service AJAX doit retourner le même contrat que le contexte initial : ```text courses visiblecount totalcount statuslabel hasmore page perpage ``` Il ne doit pas reconstruire une logique parallèle. --- ## Critères d’acceptation ### Avant filtre Le rendu initial doit afficher une carte comme ceci : ```text Titre du cours Résumé du cours Voie affichée sans label Code affiché sans label ``` ### Après filtre Après sélection d’une voie : ```text - les cartes gardent exactement le même HTML structurel - les libellés “Voie” et “Numéro de cours” ne reviennent pas - le statut “Cours affichés” est mis à jour - le résultat visuel reste cohérent avec le rendu initial ``` ### Statut de page Avant filtre : ```text Cours affichés 114 / 114 ``` Après filtre : ```text Cours affichés 14 / 114 ``` ou toute valeur réelle selon le filtre. ### Aucun ciblage fragile Interdit : ```text - cibler le texte “Cours affichés” - reconstruire les cartes en DOM manuel dans JS - répliquer la logique de filtrage dans plusieurs fichiers - utiliser metadata comme fallback non typé pour deviner les champs cours ``` --- ## Commandes de validation ### Build AMD Depuis la racine Moodle locale : ```powershell Set-Location C:\mycode\UCKK\moodle\moodle npx grunt amd --root=public/local/uckk --no-color ``` ### Purge caches ```powershell php .\admin\cli\purge_caches.php ``` ### Smoke local ```powershell Invoke-WebRequest http://127.0.0.1:8000/local/uckk/courses.php ``` ### Vérification navigateur Avant filtre : ```js document.querySelector('[data-region="course-count-summary"]')?.textContent.trim() ``` Après filtre : ```js document.querySelector('[data-region="course-count-summary"]')?.textContent.trim() ``` Les deux valeurs doivent refléter l’état réel de l’explorateur. --- ## Risques ### Risque 1 — Ancien JS servi par Moodle Si `amd/src/course_explorer.js` change, il faut rebuild AMD. Sinon la page filtrée continuera à utiliser l’ancien comportement. ### Risque 2 — Caches Moodle Les templates Mustache et JS compilés peuvent rester en cache. Toujours purger après modification : ```powershell php .\admin\cli\purge_caches.php ``` ### Risque 3 — Contrat PHP/AJAX divergent Si `courses.php` et `search_public_courses.php` ne passent pas par la même classe de service, les divergences reviendront. --- ## Non-objectifs de cette passe Ne pas modifier : ```text theme/uckk/* academic_registry_json/* admin/tool/uckkseed/* course/format/uckk/* ``` Ne pas modifier le seed ou les données de cours. Ne pas modifier la taxonomie pédagogique. Ne pas faire de refonte visuelle globale. --- ## Résumé final Cette passe doit transformer l’explorateur de cours public en composant propre : ```text Un service de données Un contrat stable Un partial de carte Un statut DOM stable Un JS qui orchestre seulement ``` Objectif : éliminer les écarts entre rendu initial et rendu filtré. ================================================================================================ FILE: docs/uckk-style-system-officiel.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 6fc95095c489db740b02098e76faebc39311f37d7d2858cd7cb646a38a3e7328 CONTENT_BYTES: 21737 ================================================================================================ # UCKK — Documentation officielle du système de styles public **Document :** Guide officiel du style public UCKK **Composant :** `local_uckk` **Portée :** Pages institutionnelles publiques UCKK dans Moodle **Statut :** Référence d’implémentation **Version :** 1.2.0 **Date :** 2026-06-22 --- ## 1. Objet Ce document définit le système de styles officiel des pages publiques UCKK. Il sert à centraliser l’identité visuelle, les règles de nommage, les composants d’interface, les limites d’intervention et les critères de qualité pour les pages institutionnelles publiques du plugin Moodle `local_uckk`. Le but est d’éviter le patchage, les styles dispersés, les classes concurrentes et les comportements visuels incohérents. --- ## 2. Principe directeur Les pages publiques UCKK doivent donner l’impression d’une **cité-école sérieuse, expérimentale, civique et documentée**. Elles ne doivent pas ressembler à : - un Moodle brut; - un portail universitaire générique; - une landing page de startup; - une interface fantasy chaotique; - un patchwork de styles locaux; - une vitrine de certification; - un savoir placé derrière un paywall. Elles doivent exprimer : - la clarté institutionnelle; - la lisibilité; - la rigueur; - la mémoire; - la preuve; - la méthode; - la diffusion ouverte du savoir; - la bibliothèque publique vivante; - le théâtre public responsable; - l’identité visuelle UCKK. --- ## 3. Canon visuel Le style UCKK public est : > **Rétrofuturisme civique encyclopédique** ou : > **Affiche institutionnelle utopique néo-académique** Il combine : - parchemin; - vert pétrole profond; - or vieilli; - encre noire-verte; - typographie institutionnelle; - grilles sobres; - cartes lisibles; - bordures fines; - hiérarchie documentaire; - symbolique sans excès fantasy. Le style doit servir une idée simple : UCKK ouvre une bibliothèque publique vivante et un cadre d’apprentissage modernisé. Le design ne doit pas suggérer un accès payant au savoir ni placer la question de la certification au centre de l’expérience publique. --- ## 4. Portée du style Le fichier de style public agit uniquement sur les pages publiques du plugin `local_uckk`. ### Inclus Le système couvre : - Accueil; - À propos; - Voies; - Cours; - Défis; - Assemblées; - Intégrité; - Archives; - Actualités; - Contact; - navigation publique UCKK; - héros de page; - cartes; - notices; - tableaux; - listes; - appels à action; - métadonnées; - sections documentaires. ### Exclu Le système ne doit pas prendre possession de : - la navigation principale Moodle; - les drawers Moodle; - les contrôles d’édition; - les formulaires Moodle génériques; - les interfaces de notation; - les rapports administratifs; - les pages système; - les activités Moodle qui ont leur propre UI; - les workflows internes; - les décisions de permission; - les règles de reconnaissance; - les cas d’intégrité. --- ## 5. Fichiers propriétaires du style public Le système officiel repose sur ces fichiers. ```text public/local/uckk/styles.css public/local/uckk/templates/public_page.mustache public/local/uckk/classes/output/public_page.php public/local/uckk/classes/local/public_pages.php ``` ### Rôle des fichiers | Fichier | Rôle | |---|---| | `styles.css` | Source unique du style public UCKK pour `local_uckk` | | `public_page.mustache` | Template unique des pages publiques | | `classes/output/public_page.php` | Objet de rendu Moodle vers Mustache | | `classes/local/public_pages.php` | Registre central des pages, navigation et définitions | Les contrôleurs publics comme `index.php`, `about.php`, `contact.php`, etc., doivent rester minces. --- ## 6. Source unique de vérité Le style public doit suivre ce principe : ```text 1 système 1 template 1 helper central 1 fichier CSS 10 contrôleurs minces ``` Les pages ne doivent pas redéfinir leur propre navigation, leur propre shell ou leurs propres classes principales. --- ## 7. Contrat HTML officiel Toutes les pages publiques doivent utiliser la même structure logique. ```html
...
...
``` --- ## 8. Convention de nommage CSS La convention officielle est : ```text .local-uckk-{component} .local-uckk-{component}__{element} .local-uckk-{component}--{modifier} .is-{state} ``` Exemples : ```text .local-uckk-public-page .local-uckk-public-page--home .local-uckk-public-nav .local-uckk-public-nav__link .local-uckk-public-nav__link.is-active .local-uckk-public-card .local-uckk-public-notice ``` --- ## 9. Classes officielles ### Racine ```text .local-uckk .local-uckk-public-page .local-uckk-public-page--{slug} ``` ### Navigation ```text .local-uckk-public-nav .local-uckk-public-nav__list .local-uckk-public-nav__item .local-uckk-public-nav__link .local-uckk-public-nav__link.is-active ``` ### Hero ```text .local-uckk-public-hero .local-uckk-public-eyebrow .local-uckk-public-title .local-uckk-public-subtitle .local-uckk-public-summary .local-uckk-public-boundary ``` ### Corps ```text .local-uckk-public-body .local-uckk-public-main .local-uckk-public-aside .local-uckk-public-section .local-uckk-public-section__title .local-uckk-public-section__body ``` ### Cartes ```text .local-uckk-public-card .local-uckk-public-card__eyebrow .local-uckk-public-card__title .local-uckk-public-card__body .local-uckk-public-card__action ``` ### Notices ```text .local-uckk-public-notice .local-uckk-public-notice--institutional .local-uckk-public-notice--integrity .local-uckk-public-notice--warning .local-uckk-public-notice__title .local-uckk-public-notice__body ``` ### Tableaux ```text .local-uckk-public-table .local-uckk-public-table--equivalence ``` ### Métadonnées ```text .local-uckk-public-meta .local-uckk-public-meta__label .local-uckk-public-meta__value ``` ### Appels à action ```text .local-uckk-public-cta .local-uckk-public-cta__title .local-uckk-public-cta__body .local-uckk-public-cta__action ``` --- ## 10. Classes à abandonner Les classes suivantes ne doivent plus être utilisées dans les nouvelles pages publiques : ```text .local-uckk-public-page__nav-link .local-uckk-public-nav-link .local-uckk-kicker .local-uckk-page-title .local-uckk-page-intro .local-uckk-info-card .local-uckk-status-notice .local-uckk-equivalence-table ``` Elles peuvent exister temporairement dans le code hérité, mais ne doivent plus être la base du système officiel. --- ## 11. Design tokens Les tokens doivent être définis dans la racine `.local-uckk`. ```css .local-uckk { --uckk-ink: var(--theme-uckk-ink, #172321); --uckk-ink-soft: var(--theme-uckk-ink-soft, #2f3f3b); --uckk-ink-muted: var(--theme-uckk-ink-muted, #52625e); --uckk-petrol: var(--theme-uckk-petrol, #1e6864); --uckk-petrol-dark: var(--theme-uckk-petrol-dark, #164c49); --uckk-petrol-soft: var(--theme-uckk-petrol-soft, #dbecea); --uckk-petrol-wash: var(--theme-uckk-petrol-wash, rgba(30, 104, 100, 0.08)); --uckk-parchment: var(--theme-uckk-parchment, #f6f0df); --uckk-parchment-light: var(--theme-uckk-parchment-light, #fbf7eb); --uckk-parchment-deep: var(--theme-uckk-parchment-deep, #e6dcc2); --uckk-gold: var(--theme-uckk-gold, #b99045); --uckk-gold-dark: var(--theme-uckk-gold-dark, #7f642f); --uckk-gold-wash: var(--theme-uckk-gold-wash, rgba(185, 144, 69, 0.12)); --uckk-card: var(--theme-uckk-card, #fffaf0); --uckk-line: var(--theme-uckk-line, rgba(23, 35, 33, 0.16)); --uckk-shadow: var(--theme-uckk-shadow, 0 16px 36px rgba(23, 35, 33, 0.11)); --uckk-shadow-soft: var(--theme-uckk-shadow-soft, 0 7px 18px rgba(23, 35, 33, 0.075)); --uckk-radius: var(--theme-uckk-radius, 0.9rem); --uckk-radius-small: var(--theme-uckk-radius-small, 0.55rem); --uckk-public-base-width: var(--theme-uckk-public-max-width, 1420px); --uckk-public-max-width: min(calc(var(--uckk-public-base-width) + 3.5rem), 1480px); --uckk-public-gutter: clamp(0.75rem, 1.5vw, 1.55rem); --uckk-public-content-inset: var(--theme-uckk-public-content-inset, clamp(1rem, 2vw, 1.75rem)); } ``` Les tokens de largeur actuels ne sont plus limités à `1180px` pour toutes les pages. Le rail public peut aller jusqu’à environ `1480px` selon le layout, avec des variantes standard, wide ou full. --- ## 12. Couleurs officielles | Usage | Token | Valeur | |---|---:|---:| | Texte principal | `--uckk-ink` | `#172321` | | Texte secondaire | `--uckk-ink-soft` | `#2f3f3b` | | Marque principale | `--uckk-petrol` | `#1e6864` | | Marque sombre | `--uckk-petrol-dark` | `#164c49` | | Fond parchemin | `--uckk-parchment` | `#f6f0df` | | Fond clair | `--uckk-parchment-light` | `#fbf7eb` | | Or vieilli | `--uckk-gold` | `#b99045` | | Or sombre | `--uckk-gold-dark` | `#7f642f` | | Bronze | `--uckk-bronze` | `#9b7441` | | Bleu-gris | `--uckk-bluegrey` | `#5f7876` | | Carte | `--uckk-card` | `#fffaf0` | --- ## 12.1 Canvas public, rail et motif héraldique Le style public utilise un canvas décoratif limité aux pages publiques `local_uckk`. Le canvas officiel est porté par : ```text body.pagelayout-local_uckk_public body:has(.local-uckk-public-page) #page #page.drawers ``` Il sert à poser : ```text - le fond parchemin général ; - le rail central de contenu ; - le motif héraldique latéral sur grand écran. ``` Le motif héraldique est défini par : ```css --uckk-side-motif-url: var( --theme-uckk-side-motif-url, url("/local/uckk/pix/heraldic-mosaic.gif") ); ``` Sur desktop, ce motif peut être répété autour du rail central. Il ne doit jamais nuire à la lecture du contenu central. Sur mobile, le motif héraldique doit être désactivé complètement. Il ne doit pas apparaître sous forme de tranche, de bande latérale, de reste de tile ou de fragment derrière le centre de la page. Règle officielle mobile : ```css @media (max-width: 767.98px) { body.pagelayout-local_uckk_public, body:has(.local-uckk-public-page), body.pagelayout-local_uckk_public #page, body:has(.local-uckk-public-page) #page, body.pagelayout-local_uckk_public #page.drawers, body:has(.local-uckk-public-page) #page.drawers { background-color: var(--uckk-page-ground) !important; background-image: none !important; background-repeat: no-repeat !important; background-size: auto !important; background-position: 0 0 !important; background-attachment: scroll !important; } } ``` Cette règle appartient à `local/uckk/styles.css`, parce qu’elle concerne le canvas des pages publiques `local_uckk`. Elle ne doit pas être déplacée dans `theme/uckk/scss/navigation.scss` ni traitée comme un problème de logo ou de barre de navigation. --- ## 13. Typographie ### Titres Les titres principaux utilisent une sérif institutionnelle. ```css font-family: Georgia, "Times New Roman", serif; ``` Usage : - titre de page; - titres de section; - titres de cartes importantes; - titres de notices. ### Texte courant Le texte courant hérite de Moodle/Boost pour préserver la compatibilité. Il doit rester : - lisible; - suffisamment grand; - sobre; - sans surcharge décorative. ### Hiérarchie recommandée | Élément | Taille | |---|---:| | Titre de page | `clamp(2rem, 4vw, 3.35rem)` | | Titre de section | `clamp(1.35rem, 2.2vw, 1.85rem)` | | Intro | `clamp(1rem, 1.4vw, 1.15rem)` | | Texte courant | `1rem` | | Métadonnées | `0.82rem` | --- ## 14. Navigation publique La navigation doit être : - visible; - compacte; - lisible; - utilisable au clavier; - clairement active; - cohérente sur toutes les pages. ### État actif L’état actif doit avoir un contraste fort. ```css .local-uckk-public-nav__link.is-active, .local-uckk-public-nav__link[aria-current="page"] { background: var(--uckk-petrol); color: var(--uckk-parchment-light); border-color: var(--uckk-gold); } ``` Le texte actif ne doit jamais avoir la même couleur que le fond. --- ## 15. Boutons Les boutons UCKK doivent respecter Moodle/Bootstrap tout en portant l’identité UCKK. ### Primaire ```text fond : vert pétrole texte : parchemin clair bordure : vert pétrole sombre ou or ``` ### Secondaire ```text fond : transparent ou parchemin texte : vert pétrole sombre bordure : vert pétrole ``` ### Interdit - bouton actif sans contraste; - texte vert sur fond vert; - fond or saturé avec texte blanc faible; - `!important` sauf justification exceptionnelle; - bouton qui change de taille au hover. --- ## 16. Cartes Les cartes sont le module principal du site public. Elles doivent être : - sobres; - séparées par des bordures fines; - lisibles; - alignées; - non surchargées; - légèrement ombrées. Structure recommandée : ```html ``` --- ## 17. Notices institutionnelles Les notices ne doivent pas crier. Elles doivent encadrer, clarifier et protéger l’institution. Notice officielle courte : > Reconnaissances internes UCKK — attestations de parcours propres à la cité-école, non encore reconnues par l’État. Cette notice peut apparaître : - sur À propos; - sur Voies; - sur Contact; - dans le pied de page public; - dans les pages de reconnaissance. --- ## 18. Tableaux Les tableaux UCKK servent aux repères institutionnels. Ils doivent être : - sobres; - lisibles; - à bordure fine; - horizontaux sur desktop; - scrollables sur mobile. Exemple : tableau d’équivalences d’appellations. Colonnes recommandées : ```text Ancienne appellation Durée cumulative Niveau UCKK Titre interne Parchemin UCKK ``` --- ## 19. Responsive ### Desktop - rail public centré jusqu’à environ `1480px` selon le layout ; - largeur standard possible autour de `1180px` pour les pages non larges ; - grilles sobres, souvent en 2 colonnes pour les cartes ; - aside possible à droite ; - motif héraldique latéral autorisé comme canvas décoratif, hors du contenu central. ### Tablette - navigation flexible ; - cartes en 1 ou 2 colonnes selon l’espace ; - aside replié sous le contenu ou en grille ; - marges et gouttières réduites ; - motif décoratif toléré seulement s’il ne nuit pas au rail central. ### Mobile - navigation scrollable ou liste compacte ; - tableaux en scroll horizontal ; - cartes pleine largeur ; - titres réduits mais lisibles ; - aside pleine largeur ; - motif héraldique latéral interdit ; - aucune image répétée, tranche d’armoiries ou tile décoratif ne doit apparaître derrière le contenu. ### Règle mobile obligatoire Sur les écrans `max-width: 767.98px`, les fonds décoratifs de `body`, `#page` et `#page.drawers` doivent être neutralisés pour les pages publiques `local_uckk`. La règle doit rester dans `local/uckk/styles.css`, non dans le thème global, car elle corrige le canvas propre au contrat public `local_uckk`. --- ## 20. Accessibilité Le système doit respecter : - contraste suffisant; - `aria-current="page"` pour la navigation active; - focus visible; - titres hiérarchiques; - liens explicites; - absence d’information uniquement par couleur; - tables lisibles; - contenu accessible sans JavaScript. ### Focus officiel ```css .local-uckk :focus-visible { outline: 3px solid rgba(185, 144, 69, 0.55); outline-offset: 3px; } ``` --- ## 21. Règles d’intégration Moodle ### Styles Chaque page publique doit charger : ```php $PAGE->requires->css(new moodle_url('/local/uckk/styles.css')); ``` ou passer par un helper central qui le fait. ### Contrôleur mince Un contrôleur public idéal : ```php header(); echo $OUTPUT->render(new \local_uckk\output\public_page('contact')); echo $OUTPUT->footer(); ``` Le contrôleur ne doit pas contenir : - navigation; - cartes codées à la main; - style inline; - logique de reconnaissance; - logique de permission complexe; - HTML massif. --- ## 22. Relation avec `theme_uckk` Le plugin `local_uckk` possède le style des **pages publiques institutionnelles UCKK**. Le thème `theme_uckk` possède : - l’identité globale; - les variables visuelles globales; - l’intégration Boost; - le header général; - les styles Moodle partagés. Règle : ```text local_uckk/styles.css → pages publiques UCKK seulement theme_uckk/scss/*.scss → thème Moodle global et identité visuelle générale ``` Le plugin local ne doit pas corriger le header global Moodle. Le thème ne doit pas contenir la logique des pages publiques. Exception importante : le canvas public `body/#page/#page.drawers` utilisé uniquement par les pages `local_uckk` appartient à `local/uckk/styles.css`. Le motif héraldique latéral, même s’il participe à l’identité visuelle globale, est appliqué par le style public et doit donc être corrigé dans `local_uckk` lorsqu’il affecte les pages publiques. Règle de décision : ```text Logo, navbar, menu utilisateur, Boost chrome -> theme_uckk. Rail public, hero, cartes, notices, métadonnées, motif latéral local_uckk -> local/uckk/styles.css. ``` --- ## 23. Interdictions Interdit dans le style public : ```text styles inline navigation recopiée dans chaque page !important comme stratégie principale couleurs codées hors tokens nouvelles classes sans convention CSS global non scopé prise de contrôle des pages Moodle core patch en bas de fichier sans refactor mélange de plusieurs conventions de classes motif héraldique visible sur smartphone correction du canvas public dans navigation.scss confusion entre logo de navbar et background décoratif de page ``` --- ## 24. Critères de qualité Une page publique UCKK est acceptée si : - elle utilise le template officiel; - elle utilise la navigation officielle; - elle charge `styles.css`; - elle ne redéfinit pas son propre système; - elle affiche clairement son état actif; - elle respecte les couleurs officielles; - elle reste lisible sur mobile; - elle n’affiche pas de chaîne manquante; - elle ne casse pas Moodle; - elle présente l’UCKK comme bibliothèque publique vivante et cadre d’apprentissage ouvert; - elle ne vend pas une promesse de certification; - elle limite la reconnaissance interne à une notice sobre, si nécessaire; - elle demeure cohérente avec le canon UCKK. --- ## 25. Checklist QA ### PHP ```powershell C:\php\8.4\php.exe -l public\local\uckk\index.php C:\php\8.4\php.exe -l public\local\uckk\classes\local\public_pages.php C:\php\8.4\php.exe -l public\local\uckk\classes\output\public_page.php ``` ### Cache ```powershell C:\php\8.4\php.exe admin\cli\purge_caches.php ``` ### Pages Tester : ```text /local/uckk/index.php /local/uckk/about.php /local/uckk/programs.php /local/uckk/courses.php /local/uckk/challenges.php /local/uckk/assemblies.php /local/uckk/integrity.php /local/uckk/archives.php /local/uckk/news.php /local/uckk/contact.php ``` ### À vérifier visuellement ```text navigation uniforme état actif lisible pas de texte sur fond de même couleur cartes alignées titres cohérents notices sobres aucune répétition défensive sur l’accréditation mobile acceptable tableaux scrollables aucun motif héraldique visible sur smartphone aucune tranche de background décoratif derrière le contenu central fond public mobile uniforme après purge des caches ``` --- ## 26. Politique de migration La migration doit être faite proprement. ### Étape unique Remplacer ensemble : ```text public/local/uckk/styles.css public/local/uckk/templates/public_page.mustache public/local/uckk/classes/output/public_page.php public/local/uckk/classes/local/public_pages.php ``` Puis simplifier les contrôleurs publics. ### À éviter Ne pas corriger page par page avec des patchs indépendants. Ne pas ajouter des exceptions pour chaque page. Ne pas résoudre un problème de contraste avec un bloc isolé si le système de classes est incohérent. --- ## 27. Glossaire visuel | Terme | Définition | |---|---| | Shell public | Structure commune d’une page publique UCKK | | Hero | Bandeau principal d’une page | | Notice | Encadré institutionnel ou canonique | | Carte | Module de contenu compact | | CTA | Appel à action | | Token | Variable CSS officielle | | État actif | Page courante dans la navigation | | Boundary notice | Notice de frontière institutionnelle | | Canon visuel | Ensemble des règles symboliques et graphiques UCKK | --- ## 28. Résumé exécutable Le système officiel est : ```text Un seul style public. Un seul template. Un seul registre de pages. Des contrôleurs minces. Des classes cohérentes. Des tokens centralisés. Un canvas public documenté. Un motif héraldique autorisé sur desktop. Aucun motif héraldique sur smartphone. Aucun patch local non documenté. Aucune prise de contrôle de Moodle core. ``` La priorité : ```text lisible institutionnel ouvert sobre cohérent canonique maintenable ``` ================================================================================================ FILE: docs/UCKK_Moodle_Source_Runtime_Sync.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: e8e5c2df5132d027935c8a45a255851035d044ee3fbb23a3cb0f50a16b579de8 CONTENT_BYTES: 11501 ================================================================================================ # UCKK Moodle — source unique, runtime Moodle et synchronisation ## Objectif Le projet Moodle complet n’est pas le repo GitHub UCKK. Moodle reste un **runtime séparé**, tandis que le repo `uckk-moodle` contient les composants UCKK à versionner, modifier, committer et pousser. La règle finale est : ```text uckk-moodle = source Git unique moodle\moodle\public = runtime Moodle copié / généré / lancé ``` Les composants UCKK ne doivent pas être moitié dans le runtime, moitié dans le repo, ni dépendre d’un mélange fragile de junctions. --- ## Dossiers principaux ### Runtime Moodle ```text C:\mycode\UCKK\moodle\moodle\public ``` Ce dossier contient l’installation Moodle complète : ```text - Moodle core - vendor - admin - course - mod - theme - local - config.php - scripts CLI Moodle ``` Il sert à : ```text - démarrer Moodle localement - tester dans le navigateur - purger les caches Moodle - exécuter les commandes CLI Moodle - contenir la copie active des plugins UCKK au moment du test ``` Exemple : ```powershell cd "C:\mycode\UCKK\moodle\moodle\public" php -S localhost:8000 -t . ``` --- ### Repo source UCKK ```text C:\mycode\UCKK\uckk-moodle ``` Ce dossier est le repo GitHub UCKK. Il sert à : ```text - modifier le code UCKK - suivre les changements avec git - commit / push vers GitHub - servir de source unique pour les composants UCKK ``` Exemple : ```powershell cd "C:\mycode\UCKK\uckk-moodle" git status ``` --- ## Principe final Toujours modifier le code UCKK dans : ```text C:\mycode\UCKK\uckk-moodle ``` Toujours lancer/tester Moodle depuis : ```text C:\mycode\UCKK\moodle\moodle\public ``` Le runtime Moodle reçoit une copie fraîche des composants UCKK via un script de synchronisation lancé avant le démarrage de Moodle. --- ## Pourquoi ne plus utiliser les junctions Les junctions Windows peuvent sembler pratiques, mais ils changent la manière dont PHP résout certains chemins avec `__DIR__` et `realpath()`. Exemple problématique : ```php require_once(__DIR__ . '/../../config.php'); ``` Ce code est normal dans un plugin Moodle quand le fichier est physiquement sous : ```text C:\mycode\UCKK\moodle\moodle\public\local\uckk ``` Il pointe alors vers : ```text C:\mycode\UCKK\moodle\moodle\public\config.php ``` Mais si `public\local\uckk` est un junction vers : ```text C:\mycode\UCKK\uckk-moodle\local\uckk ``` PHP peut résoudre `__DIR__` vers le repo source, puis chercher : ```text C:\mycode\UCKK\uckk-moodle\config.php ``` Ce fichier n’existe pas. Résultat : le runtime casse. Conclusion : ```text Les plugins Moodle exécutables doivent être physiquement copiés dans le runtime Moodle. Le repo reste la source unique, mais le runtime exécute des copies. ``` --- ## Composants UCKK à synchroniser Les composants UCKK à copier depuis le repo vers Moodle runtime sont : ```text local\uckk mod\uckkarchive mod\uckkchallenge mod\uckkassembly theme\uckk admin\tool\uckkseed admin\tool\uckkintegrity course\format\uckk ai\provider\uckk ``` Selon l’évolution du projet, ajouter ici les autres composants UCKK : ```text blocks\... availability\... ``` --- ## Workflow quotidien ### 1. Modifier le code Toujours ouvrir et modifier : ```text C:\mycode\UCKK\uckk-moodle ``` Exemples : ```text Core UCKK : C:\mycode\UCKK\uckk-moodle\local\uckk Challenge : C:\mycode\UCKK\uckk-moodle\mod\uckkchallenge Assembly : C:\mycode\UCKK\uckk-moodle\mod\uckkassembly Archive : C:\mycode\UCKK\uckk-moodle\mod\uckkarchive Format : C:\mycode\UCKK\uckk-moodle\course\format\uckk Seed tool : C:\mycode\UCKK\uckk-moodle\admin\tool\uckkseed Integrity : C:\mycode\UCKK\uckk-moodle\admin\tool\uckkintegrity Theme : C:\mycode\UCKK\uckk-moodle\theme\uckk AI provider: C:\mycode\UCKK\uckk-moodle\ai\provider\uckk ``` --- ### 2. Lancer la petite app Moodle La petite app de lancement doit faire automatiquement : ```text 1. vérifier que les chemins existent 2. vérifier qu’aucune cible UCKK dans public n’est un junction 3. créer un backup des composants UCKK actuellement actifs dans Moodle runtime 4. copier les composants UCKK depuis uckk-moodle vers moodle\moodle\public 5. purger les caches Moodle 6. lancer Moodle ``` Ordre logique : ```text uckk-moodle → sync vers moodle\moodle\public → purge caches → php -S localhost:8000 -t . ``` --- ### 3. Tester dans Moodle Moodle est lancé depuis : ```text C:\mycode\UCKK\moodle\moodle\public ``` Puis ouvrir : ```text http://localhost:8000 ``` ou : ```text http://127.0.0.1:8000 ``` --- ### 4. Valider PHP Exemples : ```powershell cd "C:\mycode\UCKK\moodle\moodle\public" php -l .\local\uckk\programs.php php -l .\mod\uckkchallenge\view.php php -l .\mod\uckkassembly\classes\output\assembly_view.php php -l .\mod\uckkarchive\classes\output\archive_view.php ``` Ces fichiers sont testés dans le runtime, mais leur source officielle reste dans : ```text C:\mycode\UCKK\uckk-moodle ``` --- ### 5. Commit / push Toujours depuis le repo source : ```powershell cd "C:\mycode\UCKK\uckk-moodle" git status git add -A git commit -m "Message du changement" git push ``` --- ## Script de synchronisation recommandé Créer : ```text C:\mycode\UCKK\uckk-moodle\tools\sync-to-local-moodle.ps1 ``` Contenu recommandé : ```powershell $ErrorActionPreference = "Stop" $REPO = "C:\mycode\UCKK\uckk-moodle" $MOODLE = "C:\mycode\UCKK\moodle\moodle\public" $BACKUPROOT = "C:\mycode\UCKK\moodle-runtime-backups" $timestamp = Get-Date -Format "yyyyMMdd_HHmmss" $backup = Join-Path $BACKUPROOT "uckk_custom_$timestamp" $items = @( @{ Source = "local\uckk"; Target = "local\uckk" }, @{ Source = "mod\uckkarchive"; Target = "mod\uckkarchive" }, @{ Source = "mod\uckkchallenge"; Target = "mod\uckkchallenge" }, @{ Source = "mod\uckkassembly"; Target = "mod\uckkassembly" }, @{ Source = "theme\uckk"; Target = "theme\uckk" }, @{ Source = "admin\tool\uckkseed"; Target = "admin\tool\uckkseed" }, @{ Source = "admin\tool\uckkintegrity"; Target = "admin\tool\uckkintegrity" }, @{ Source = "course\format\uckk"; Target = "course\format\uckk" }, @{ Source = "ai\provider\uckk"; Target = "ai\provider\uckk" } ) Write-Host "UCKK sync starting..." -ForegroundColor Cyan Write-Host "Source: $REPO" Write-Host "Runtime: $MOODLE" Write-Host "Backup: $backup" if (-not (Test-Path $REPO)) { throw "Repo not found: $REPO" } if (-not (Test-Path $MOODLE)) { throw "Moodle runtime not found: $MOODLE" } if (-not (Test-Path (Join-Path $MOODLE "config.php"))) { throw "Moodle config.php not found in runtime: $MOODLE" } New-Item -ItemType Directory -Force -Path $backup | Out-Null foreach ($item in $items) { $src = Join-Path $REPO $item.Source $dst = Join-Path $MOODLE $item.Target $bak = Join-Path $backup $item.Target if (-not (Test-Path $src)) { Write-Host "SKIP missing source: $src" -ForegroundColor Yellow continue } if (Test-Path $dst) { $existing = Get-Item $dst if ($existing.LinkType) { throw "Target is a junction/symlink and must be removed before sync: $dst" } New-Item -ItemType Directory -Force -Path (Split-Path $bak) | Out-Null robocopy $dst $bak /MIR /XD ".git" "node_modules" ".scannerwork" /XF "*.tmp" "*.log" | Out-Host if ($LASTEXITCODE -gt 7) { throw "Backup robocopy failed for $($item.Target), exit code $LASTEXITCODE" } } New-Item -ItemType Directory -Force -Path (Split-Path $dst) | Out-Null Write-Host "Sync $($item.Source) -> $($item.Target)" -ForegroundColor Green robocopy $src $dst /MIR ` /XD ".git" "node_modules" ".scannerwork" ` /XF "*.tmp" "*.log" ` | Out-Host if ($LASTEXITCODE -gt 7) { throw "Sync robocopy failed for $($item.Source), exit code $LASTEXITCODE" } } Write-Host "Purging Moodle caches..." -ForegroundColor Cyan Push-Location $MOODLE php -r "define('CLI_SCRIPT', true); require 'config.php'; purge_all_caches(); echo 'Caches purged' . PHP_EOL;" Pop-Location Write-Host "UCKK sync complete." -ForegroundColor Green ``` --- ## Intégration dans la petite app de lancement Avant de lancer Moodle, l’app doit exécuter : ```powershell pwsh -ExecutionPolicy Bypass -File "C:\mycode\UCKK\uckk-moodle\tools\sync-to-local-moodle.ps1" ``` Puis lancer Moodle : ```powershell cd "C:\mycode\UCKK\moodle\moodle\public" php -S localhost:8000 -t . ``` La petite app peut afficher : ```text 1. Source repo détectée 2. Runtime Moodle détecté 3. Backup créé 4. Sync terminée 5. Caches purgés 6. Moodle lancé ``` --- ## Backups runtime Les backups de composants UCKK actifs sont créés ici : ```text C:\mycode\UCKK\moodle-runtime-backups ``` Nom typique : ```text uckk_custom_YYYYMMDD_HHMMSS ``` Ces backups servent à revenir rapidement à l’état précédent du runtime si une synchronisation introduit un problème. Ils ne sont pas la source officielle. La source officielle reste : ```text C:\mycode\UCKK\uckk-moodle ``` --- ## Vérifier qu’il ne reste pas de junctions UCKK Commande de vérification : ```powershell $RUNTIME = "C:\mycode\UCKK\moodle\moodle\public" $paths = @( "$RUNTIME\local\uckk", "$RUNTIME\mod\uckkchallenge", "$RUNTIME\mod\uckkassembly", "$RUNTIME\mod\uckkarchive", "$RUNTIME\course\format\uckk", "$RUNTIME\admin\tool\uckkseed", "$RUNTIME\admin\tool\uckkintegrity", "$RUNTIME\theme\uckk", "$RUNTIME\ai\provider\uckk" ) foreach ($path in $paths) { if (Test-Path $path) { Get-Item $path | Select-Object FullName, LinkType, Target } } ``` Résultat attendu : ```text LinkType = Target = ``` Aucune cible UCKK active dans `public` ne doit être un junction. --- ## À ne plus faire Ne plus créer de junctions UCKK dans : ```text C:\mycode\UCKK\moodle\moodle\public ``` Ne plus modifier directement les fichiers UCKK dans : ```text C:\mycode\UCKK\moodle\moodle\public ``` Ne plus utiliser un workflow où certains composants sont en junction et d’autres en copie physique. Ne plus utiliser une app de sync qui remplace arbitrairement des dossiers sans backup. Ne pas créer de `config.php` shim dans : ```text C:\mycode\UCKK\uckk-moodle ``` --- ## Déploiement serveur Sur un serveur, ne pas déployer les composants UCKK comme symlinks vers un repo externe. Déployer les plugins comme dossiers physiques dans l’installation Moodle : ```text /path/to/moodle/local/uckk /path/to/moodle/mod/uckkarchive /path/to/moodle/mod/uckkchallenge /path/to/moodle/mod/uckkassembly /path/to/moodle/theme/uckk /path/to/moodle/admin/tool/uckkseed /path/to/moodle/admin/tool/uckkintegrity /path/to/moodle/course/format/uckk /path/to/moodle/ai/provider/uckk ``` Ensuite exécuter les commandes Moodle habituelles : ```bash php admin/cli/upgrade.php php admin/cli/purge_caches.php ``` --- ## Résumé court ```text Modifier ici : C:\mycode\UCKK\uckk-moodle Tester ici : C:\mycode\UCKK\moodle\moodle\public Git ici : C:\mycode\UCKK\uckk-moodle Backup ici : C:\mycode\UCKK\moodle-runtime-backups ``` Le runtime Moodle reçoit les composants UCKK par synchronisation contrôlée avant lancement. ```text uckk-moodle → sync-to-local-moodle.ps1 → moodle\moodle\public → purge caches → launch Moodle ``` Source unique : `uckk-moodle`. Runtime : `moodle\moodle\public`. Aucune junction UCKK active dans le runtime. ================================================================================================ FILE: docs/UCKK_Notes_Operationnelles_Conversation_2026-06-01.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 0cc11b9afef8b019e56f4cd8249a11075d49321b2f7d9f59f59489d82a0161ea CONTENT_BYTES: 7721 ================================================================================================ # UCKK — Notes opérationnelles apprises pendant l’intervention _Date : 2026-06-01_ _Portée : éléments compris pendant le dépannage, mais pas assez explicites dans les docs actuelles._ --- ## 1. Modèle mental simplifié Il faut toujours distinguer trois choses : ```text Repo source = les fichiers officiels versionnés Git Runtime Moodle = le Moodle qui roule vraiment DB Moodle = ce que Moodle affiche vraiment pour certaines données ``` Exemple : ```text academic_registry_json/categories.json ``` n’est pas affiché directement par Moodle. Ce fichier est une source. Il faut ensuite appliquer le seed pour écrire les catégories dans la DB Moodle. Image simple : ```text categories.json = recette seed categories = appliquer la recette DB Moodle = ce que Moodle affiche ``` --- ## 2. `academic_registry_json` n’est pas un composant runtime Ne pas traiter : ```text academic_registry_json ``` comme : ```text local/uckk mod/uckkarchive theme/uckk admin/tool/uckkseed ``` Les plugins doivent être synchronisés dans le runtime Moodle. Le registre académique JSON, lui, doit rester dans le repo source et être appliqué par le seed. Flux correct : ```text modifier academic_registry_json/categories.json → git commit + push → git pull serveur → seed categories → purge caches → vérifier dans Moodle ``` --- ## 3. Le GUI ne doit pas cacher les prompts SSH/sudo Pendant l’intervention, le GUI semblait gelé parce que SSH attendait un mot de passe ou une confirmation en arrière-plan. Règle : avant d’utiliser les boutons serveur du GUI, vérifier SSH dans PowerShell : ```powershell ssh -i "$env:USERPROFILE\.ssh\id_ed25519" -o IdentitiesOnly=yes -o BatchMode=yes ubuntu@57.129.115.159 "echo OK" ``` Résultat obligatoire : ```text OK ``` Si ce test ne répond pas `OK`, ne pas cliquer : ```text Pull serveur Dry-run categories serveur Apply categories serveur Purger caches serveur ``` --- ## 4. Ajouter la clé SSH depuis PowerShell La clé privée locale existait et n’avait pas de passphrase, mais le serveur ne l’acceptait pas encore. Commande qui a corrigé l’accès SSH : ```powershell Get-Content "$env:USERPROFILE\.ssh\id_ed25519.pub" | ssh ubuntu@57.129.115.159 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys" ``` Après ça, le test SSH a répondu : ```text OK ``` Conclusion : le problème n’était pas la clé locale; le serveur ne connaissait pas encore sa clé publique. --- ## 5. Le seed UCKK ne s’applique pas avec `--force` seul Observation importante : cette commande : ```powershell ssh -tt ubuntu@57.129.115.159 "cd /var/www/moodle/public && sudo -u www-data php admin/tool/uckkseed/cli/seed.php --presetpath=/opt/uckk/uckk-moodle/academic_registry_json --preset=categories --force" ``` a retourné : ```text Mode: dry_run No distribution records will be written in this mode. ``` Donc : ```text --force seul ne suffit pas ``` Le mode réel vient de la configuration Moodle : ```text tool_uckkseed/defaultmode ``` --- ## 6. `--mode=apply` n’est pas accepté par le seed CLI actuel Cette commande a échoué : ```text --mode=apply ``` Erreur : ```text Unknown option(s): --mode=apply ``` Donc le bon chemin est : ```text 1. changer temporairement defaultmode à apply 2. lancer seed.php avec --force 3. remettre defaultmode à dry_run 4. purger les caches ``` --- ## 7. Commande d’application qui a fonctionné La partie importante qui a fonctionné : ```bash cd /var/www/moodle/public sudo -u www-data php <<'PHP' count_records('course_categories') . PHP_EOL; echo "course_non_site=" . $DB->count_records_select('course', 'id <> 1') . PHP_EOL; echo "local_uckk_program=" . $DB->count_records('local_uckk_program') . PHP_EOL; echo "local_uckk_pathway=" . $DB->count_records('local_uckk_pathway') . PHP_EOL; PHP '@ $script | ssh $server "bash -s" ``` ## 11. Purging Moodle caches After PHP, Mustache, theme, or public page changes, purge Moodle caches: ```powershell ssh ubuntu@57.129.115.159 "sudo -u www-data php /var/www/moodle/public/admin/cli/purge_caches.php && sudo systemctl reload php8.3-fpm" ``` ## 12. Files that should not be committed Do not commit local backup files or temporary patch scripts unless intentionally promoted to tooling. Examples to avoid committing: ```text *.bak.* local/uckk/courses.php.bak.before-vps-livecourses-* tools/uckk_nomenclature_patch.py # unless intentionally reviewed and accepted ``` Check before commit: ```powershell $repo = "C:\mycode\UCKK\uckk-moodle" git -C $repo status --short git -C $repo diff --cached --stat ``` ## 13. Recommended safe update flow 1. Work locally on `stabilize-runtime-20260522`. 2. Commit only reviewed files. 3. Push to GitHub. 4. Pull or deploy the branch on the server. 5. Sync source to Moodle runtime if needed. 6. Purge Moodle caches. 7. Test public pages: ```text http://57.129.115.159/local/uckk/programs.php http://57.129.115.159/local/uckk/courses.php http://57.129.115.159/course/index.php ``` 8. Test one course link: ```text http://57.129.115.159/course/view.php?id= ``` ## 14. Security notes - Never commit passwords. - Never commit private SSH keys. - Never paste database passwords into docs or chat logs. - Prefer SSH keys over password login. - If a password has been pasted publicly or into logs, rotate it. - Keep database backups outside the Git repository. ================================================================================================ FILE: mod/uckkarchive/docs/00_index.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: e32ab9c6d969a05a05034f21886fbe7c1f4de712f534275d3ea560a768f61438 CONTENT_BYTES: 21399 ================================================================================================ # 00 — Documentation Index **Path:** `docs/00_index.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Index and navigation map for the clean `mod_uckkarchive` documentation set. --- ## 1. Purpose This document is the canonical index for the `mod_uckkarchive` documentation set. The documentation defines the final target behavior for a self-contained Moodle activity module that provides: ```text archive memory media library management public Médiathèque façade public Médiathèque explorer content advisory governance cultural sensitivity tagging external/foreign media references exportable archive/media packages ``` The documentation is used to guide code generation, implementation review, testing, backup/restore design, privacy coverage, service design, UI construction, and packaging. --- ## 2. Documentation mode The documentation set uses this mode: ```text DOC_MODE = final_state_specification DOC_STYLE = descriptive DOC_TARGET = build-ready module specification ``` Rules: ```text Documentation describes the final target behavior. Documentation does not preserve historical debate. Documentation does not keep a gap register. Documentation does not use acceptance-checklist process documents. Documentation does not use release-notes process documents. Documentation does not describe required features as future optional features. ``` --- ## 3. Canonical architecture formula `mod_uckkarchive` follows this architecture formula: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` Canonical module definition: ```text mod_uckkarchive = self-contained Moodle activity module for archive memory, media library management, and content advisory governance. ``` The module is installed and governed as a Moodle module. The module owns its internal archive/media/content-advisory domain. --- ## 4. Canonical paths Source documentation path: ```text C:\mycode\UCKK\uckk-moodle\mod\uckkarchive\docs ``` Active Moodle documentation path: ```text C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive\docs ``` Source plugin path: ```text C:\mycode\UCKK\uckk-moodle\mod\uckkarchive ``` Active Moodle plugin path: ```text C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive ``` Canonical Moodle plugin path: ```text mod/uckkarchive ``` Component: ```text mod_uckkarchive ``` --- ## 5. Required alignment file Every documentation-generation conversation must start from: ```text docs/_alignment_variables.md ``` This file defines shared variables for: ```text plugin identity canonical paths active documentation set architecture formula database tables capabilities file areas media lifecycle public Médiathèque façade public Médiathèque explorer archive lifecycle validation states visibility values provenance values media relation types content advisory subsystem external works foreign media references export manifests required code files writing rules ``` Rule: ```text If another document conflicts with docs/_alignment_variables.md, update the document to match the alignment variables. ``` --- ## 6. Active documentation set Generate and maintain these documents only: ```text docs/_alignment_variables.md docs/00_index.md docs/01_architecture_decision.md docs/02_domain_boundaries.md docs/03_file_architecture.md docs/04_data_model.md docs/05_media_library.md docs/06_file_api_and_storage.md docs/07_permissions_and_roles.md docs/08_archive_workflows.md docs/09_media_workflows.md docs/10_provenance_versioning_validation.md docs/11_privacy_retention_redaction.md docs/12_backup_restore.md docs/13_services_and_ajax_api.md docs/14_events_and_audit.md docs/15_ui_templates_and_amd.md docs/16_integration_with_courses.md docs/17_integration_with_challenges.md docs/18_integration_with_assemblies.md docs/19_integration_with_integrity.md docs/20_reporting_and_exports.md docs/21_testing_strategy.md docs/22_installation.md docs/23_upgrade.md docs/24_release_spec.md docs/25_mediatheque_public_explorer.md ``` --- ## 7. Generation order Use this order when generating documents in separate conversations: ```text 1. docs/_alignment_variables.md 2. docs/00_index.md 3. docs/01_architecture_decision.md 4. docs/02_domain_boundaries.md 5. docs/03_file_architecture.md 6. docs/04_data_model.md 7. docs/05_media_library.md 8. docs/06_file_api_and_storage.md 9. docs/07_permissions_and_roles.md 10. docs/08_archive_workflows.md 11. docs/09_media_workflows.md 12. docs/10_provenance_versioning_validation.md 13. docs/11_privacy_retention_redaction.md 14. docs/12_backup_restore.md 15. docs/13_services_and_ajax_api.md 16. docs/14_events_and_audit.md 17. docs/15_ui_templates_and_amd.md 18. docs/16_integration_with_courses.md 19. docs/17_integration_with_challenges.md 20. docs/18_integration_with_assemblies.md 21. docs/19_integration_with_integrity.md 22. docs/20_reporting_and_exports.md 23. docs/21_testing_strategy.md 24. docs/22_installation.md 25. docs/23_upgrade.md 26. docs/24_release_spec.md 27. docs/25_mediatheque_public_explorer.md ``` --- ## 8. Documents not generated The clean documentation set does not generate these files: ```text docs/05_media_database_division.md docs/09_didactic_material_workflows.md docs/24_acceptance_checklist.md docs/25_known_gaps_and_corrections.md docs/26_release_notes.md docs/27_file_architecture_manifest.md ``` Replacement mapping: ```text media_database_division -> docs/05_media_library.md didactic_material_workflows -> docs/08_archive_workflows.md and docs/09_media_workflows.md acceptance_checklist -> docs/24_release_spec.md known_gaps_and_corrections -> not replaced 25_mediatheque_public_explorer -> active public Médiathèque specification release_notes -> docs/24_release_spec.md file_architecture_manifest -> docs/03_file_architecture.md ``` --- ## 9. Document summaries ### `docs/_alignment_variables.md` Defines the canonical variables used by every document. This file is the cross-document contract. All other documentation must align with it. --- ### `docs/00_index.md` Defines the active documentation set, generation order, module formula, navigation map, and cross-document consistency rules. This file is the documentation entry point. --- ### `docs/01_architecture_decision.md` Defines the core architecture decision: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` It establishes module ownership, Moodle boundary, external plugin boundaries, media as a first-class domain object, content advisory governance, and non-negotiable architecture rules. --- ### `docs/02_domain_boundaries.md` Defines ownership boundaries between `mod_uckkarchive` and other Moodle/UCKK systems. It defines what the archive may preserve, reference, display, summarize, export, or link without becoming the authority for external workflows. --- ### `docs/03_file_architecture.md` Defines the plugin file and folder architecture. It covers: ```text root PHP files AMD files backup/restore files classes/local classes/external classes/output classes/event classes/form classes/task db files lang files templates tests pix assets ``` --- ### `docs/04_data_model.md` Defines the database schema and entity relationships. It covers archive tables, media tables, content advisory tables, external work tables, UUID rules, status fields, visibility fields, indexes, constraints, and migration expectations. --- ### `docs/05_media_library.md` Defines the internal media-library engine. It covers media objects, media versions, media collections, media relations, media tags, media source records, derivatives, thumbnails, captions, transcripts, external/foreign media references, and media lifecycle. --- ### `docs/06_file_api_and_storage.md` Defines Moodle File API usage. It covers archive file areas, media file areas, content advisory file areas, pluginfile handling, restricted access, derivative files, export files, backup/restore file handling, privacy file handling, and forbidden storage patterns. --- ### `docs/07_permissions_and_roles.md` Defines capabilities, role defaults, access rules, policy classes, restricted access, media download permissions, advisory review permissions, cultural protocol permissions, and export permissions. --- ### `docs/08_archive_workflows.md` Defines archive workflows. It covers item creation, submission, validation, revision, contestation, restriction, publication, archive item/media linking, proof workflows, Kristal workflows, and export preparation. --- ### `docs/09_media_workflows.md` Defines media workflows. It covers media creation, upload, source classification, versioning, collection membership, tagging, relation mapping, derivative generation, transcript/caption management, external work linking, and content advisory marker creation. --- ### `docs/10_provenance_versioning_validation.md` Defines provenance, versioning, validation, contestability, archive revision rules, media version rules, content review rules, human-final validation, and provenance portability. --- ### `docs/11_privacy_retention_redaction.md` Defines privacy, retention, redaction, restricted records, export redaction, advisory redaction, cultural protocol redaction, user data export, and deletion behavior. --- ### `docs/12_backup_restore.md` Defines backup and restore behavior. It covers archive records, media records, media files, media versions, collections, relations, content advisories, content markers, content reviews, external works, export manifests, ID mapping, and file restoration. --- ### `docs/13_services_and_ajax_api.md` Defines external service and AJAX API architecture. It covers archive services, media services, content advisory services, external work services, export services, parameter validation, return structures, capability gates, and policy enforcement. --- ### `docs/14_events_and_audit.md` Defines event and audit behavior. It covers archive events, media events, content marker events, external work events, export events, privacy-safe event payloads, and audit trace rules. --- ### `docs/15_ui_templates_and_amd.md` Defines UI architecture. It covers page layouts, Mustache templates, renderables, AMD modules, archive cards, media cards, content advisory panels, external work cards, validation panels, provenance panels, and client/server responsibility boundaries. --- ### `docs/16_integration_with_courses.md` Defines integration with Moodle courses. It covers course-module context, course visibility, groups, activity completion, course navigation, course content usage, and course-level archive/media access. --- ### `docs/17_integration_with_challenges.md` Defines integration with `mod_uckkchallenge`. It covers preserving challenge evidence, linking challenge outputs, archiving challenge-related media, and maintaining challenge workflow boundaries. --- ### `docs/18_integration_with_assemblies.md` Defines integration with `mod_uckkassembly`. It covers preserving assembly minutes, decisions, attachments, media, summaries, and provenance while keeping assembly decision authority outside the archive. --- ### `docs/19_integration_with_integrity.md` Defines optional integration with `tool_uckkintegrity`. It covers restricted integrity-related archive records, integrity exports, integrity evidence preservation, content warnings, cultural restrictions, and fail-closed behavior when the tool is absent. --- ### `docs/20_reporting_and_exports.md` Defines reporting and export boundaries. It covers archive-owned export packages, media export packages, collection exports, manifest format, content advisory export behavior, external work references, and separation from `report_uckk`. --- ### `docs/21_testing_strategy.md` Defines testing strategy. It covers unit tests, advanced tests, privacy tests, backup/restore tests, service tests, file API tests, media library tests, content advisory tests, external work tests, Behat tests, and regression rules. --- ### `docs/22_installation.md` Defines installation behavior. It covers Moodle installation, plugin version, database install, capabilities, tasks, services, language strings, file areas, settings, and initial configuration. --- ### `docs/23_upgrade.md` Defines upgrade behavior. It covers schema upgrades, media table introduction, content advisory table introduction, file-area normalization, capability migration, data migration, backup compatibility, and upgrade safety. --- ### `docs/24_release_spec.md` Defines release-state package expectations. It covers the final package shape, required files, excluded files, clean distribution rules, code-generation completion criteria, and packaging constraints. This document is a release specification, not a release note and not an acceptance checklist. --- ### `docs/25_mediatheque_public_explorer.md` Defines the public Médiathèque page and public Médiathèque Explorer. It covers the relationship between `local_uckk` and `mod_uckkarchive`, the public search façade, the `mod_uckkarchive_search_mediatheque` AJAX contract, public DTOs, filters, cards, targeted passages, visibility rules, cultural-protocol boundaries, content-advisory display, reusable media-library assets, and anti-duplication rules. This document is the public-surface contract for exposing a policy-filtered subset of the existing media library. It does not create a second media engine. --- ## 10. Canonical internal ownership list `mod_uckkarchive` owns: ```text archive records archive items media records media versions media files media collections media collection membership media relations media tags proof records Kristals provenance records revision history validation state restricted archive metadata restricted media metadata content advisory tags cultural sensitivity tags content tag sets content markers content reviews external works foreign media references media source records public Médiathèque search façade public Médiathèque repository/service public media DTO filtering audience suitability rules export packages export manifests ``` --- ## 11. Canonical external ownership boundaries `mod_uckkarchive` does not own: ```text grades transcripts course enrolment authority administrative registry records challenge workflow state Assembly decision authority integrity case authority institutional reporting authority public page shell ownership public navigation shell ownership ``` External ownership map: ```text Moodle gradebook = grades local_uckk = shared UCKK registry, institutional configuration, public page shell, and public navigation shell mod_uckkchallenge = challenge workflow mod_uckkassembly = assembly workflow and decisions tool_uckkintegrity = integrity procedures and case records report_uckk = institutional reporting views and institutional report exports mod_uckkarchive = archive/media/content-advisory memory layer ``` --- ## 12. Canonical database table list Archive tables: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export ``` Media tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` Content advisory and external-work tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Identifier rule: ```text id = local Moodle database primary key uuid = stable portable object identity ``` --- ## 13. Canonical capability list Archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Removed capability: ```text mod/uckkarchive:versionitem = not used ``` --- ## 14. Canonical File API areas Archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` --- ## 15. Canonical status and classification values Media states: ```text draft submitted active restricted superseded archived deleted_soft ``` Archive item statuses: ```text draft submitted under_review validated published restricted contested invalidated superseded archived ``` Validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Provenance values: ```text human ai_assisted imported system archive assembly challenge integrity media external_work content_review ``` --- ## 16. Content advisory index The content advisory subsystem covers: ```text content advisories content warnings cultural advisories cultural protocols audience suitability content markers tag sets reviews external works foreign media references ``` Canonical advisory tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Architecture rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 17. External works index External works are works not produced by UCKK but referenced, taught, reviewed, tagged, or connected to archive/media records. External work examples: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External/foreign media rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` --- ## 18. Export manifest index Canonical manifest filename: ```text manifest.json ``` The manifest includes: ```text plugin component archive id export id export timestamp export actor export reason archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` --- ## 19. Cross-document consistency rules Every document must use the same: ```text component name plugin path architecture formula database table names capability names file areas media states archive item statuses validation states visibility values provenance values content advisory terminology external work terminology export manifest terminology public Médiathèque terminology public Médiathèque Explorer terminology local_uckk public shell boundary mod_uckkarchive public data/policy boundary ``` Every document must avoid: ```text known gaps known corrections acceptance checklist release notes old architecture debate media as only generic item attachment content advisories as only a JSON field duplicating the media-library engine for the public Médiathèque creating separate Médiathèque card/detail/marker templates when existing media templates suffice placing media access decisions in local_uckk, AMD, or Mustache versionitem capability hard dependency on tool_uckkintegrity ``` --- ## 20. Implementation-use rule This documentation set is written for implementation. Each document must be usable by an AI coding conversation as a source of truth for generating: ```text PHP classes Moodle callbacks database schema upgrade steps external services public service façades events forms output classes templates AMD modules public controllers privacy provider backup/restore steps tests language strings package structure ``` --- ## 21. Final rule ```text This documentation set defines the final target behavior for implementation. Code, tests, services, UI, public Médiathèque surfaces, backup/restore, privacy, content advisory governance, and packaging must conform to these specifications. ``` ================================================================================================ FILE: mod/uckkarchive/docs/01_architecture_decision.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 1d2f6551a10d09e9f0a34ddd723e7c2ad39a75824f971ca4b96ac3246453e1ac CONTENT_BYTES: 20246 ================================================================================================ # 01 — Architecture Decision **Path:** `docs/01_architecture_decision.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Architecture decision for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Core decision `mod_uckkarchive` is a Moodle-native activity module with a self-contained internal archive, media library, and content advisory system. Canonical formula: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` The module is installed, configured, secured, rendered, backed up, restored, and governed through Moodle APIs. Inside that Moodle boundary, the module owns its own archive, media library, content advisory, cultural protocol, external work, provenance, validation, versioning, and export domain. --- ## 2. Module definition Canonical module definition: ```text mod_uckkarchive = self-contained Moodle activity module for archive memory, media library management, and content advisory governance. ``` The module is not only a file attachment feature. The module is not only an archive item list. The module is not only a didactic resource activity. The module is the UCKK archive/media/content-advisory memory layer. --- ## 3. Internal ownership `mod_uckkarchive` owns internally: ```text archive records archive items media records media versions media files media collections media collection membership media relations media tags proof records Kristals provenance records revision history validation state restricted archive metadata restricted media metadata content advisory tags cultural sensitivity tags content tag sets content markers content reviews external works foreign media references media source records audience suitability rules export packages export manifests ``` The module owns three internal engines: ```text archive engine media library engine content advisory engine ``` The archive engine manages institutional, pedagogical, evidential, validation, revision, and provenance memory. The media library engine manages media objects, versions, files, collections, tags, relations, derivatives, transcripts, captions, thumbnails, previews, and export identity. The content advisory engine manages advisories, cultural sensitivity tags, cultural protocol notes, content markers, locators, suitability rules, review state, and external work references. --- ## 4. Moodle ownership boundary `mod_uckkarchive` uses Moodle for: ```text plugin lifecycle course module context course visibility users roles capabilities groups File API Privacy API Backup API Restore API External Services API events settings language strings rendering scheduled tasks ``` `mod_uckkarchive` must not bypass Moodle’s context, capability, privacy, backup/restore, file, event, task, rendering, or service systems. Moodle remains the host platform. `mod_uckkarchive` remains the self-contained domain module inside Moodle. --- ## 5. External domain boundaries `mod_uckkarchive` must not own external UCKK or Moodle authority domains. Canonical ownership boundaries: ```text GRADE_OWNER = Moodle gradebook REGISTRY_OWNER = local_uckk CHALLENGE_OWNER = mod_uckkchallenge ASSEMBLY_OWNER = mod_uckkassembly INTEGRITY_OWNER = tool_uckkintegrity REPORT_OWNER = report_uckk ARCHIVE_OWNER = mod_uckkarchive ``` Boundary rules: ```text mod_uckkarchive does not own grades. mod_uckkarchive does not own transcripts. mod_uckkarchive does not own enrolment authority. mod_uckkarchive does not own administrative registry records. mod_uckkarchive does not own challenge workflow state. mod_uckkarchive does not own Assembly decision authority. mod_uckkarchive does not own integrity case authority. mod_uckkarchive does not own institutional reporting authority. ``` The archive may preserve records, evidence, media, attachments, summaries, content advisories, cultural protocol notes, external work references, or exported snapshots from those domains. Preservation does not transfer authority. --- ## 6. Integrity integration decision `tool_uckkintegrity` is an optional integration. Ordinary archive, media-library, and content-advisory operation must not require `tool_uckkintegrity`. Integrity-specific archive features must be hidden, disabled, or fail closed when `tool_uckkintegrity` is absent. The archive may preserve integrity-related evidence, media, restricted records, content markers, provenance, and export packages. The archive does not own integrity case procedure, findings, sanctions, appeals, or closure. --- ## 7. Archive decision Archive items are first-class memory objects. Canonical archive table: ```text uckkarchive_item ``` Archive items represent preserved UCKK memory such as: ```text proof decision snapshot minutes challenge result course work portfolio item Kristal source integrity summary public summary institutional source pedagogical source ``` Archive items may link to media objects, content advisories, content markers, external works, Kristals, proofs, collections, provenance records, revision records, and export manifests. Archive items are not grades. Archive items are not administrative records. Archive items are not final Assembly authority. Archive items are not integrity case authority. --- ## 8. Media-library decision Media is a first-class domain object in the target architecture. Canonical decision: ```text media object = uckkarchive_media media version = uckkarchive_media_version media collection = uckkarchive_media_collection media relation = uckkarchive_media_relation media tag = uckkarchive_media_tag ``` Media is not merely a subtype of `uckkarchive_item`. Media is not stored as a public folder. Media is not stored directly as binary data in custom database fields. Media files are stored through Moodle File API. Media metadata, identity, versions, relations, collections, tags, lifecycle state, file references, source records, and advisory links are stored in archive-owned tables. --- ## 9. Content advisory decision Content advisories are first-class domain objects. The content advisory system manages: ```text content advisories cultural sensitivity tags cultural protocol tags content tag sets content markers content reviews external works foreign media references media source records audience suitability rules review states ``` Canonical rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` The system must support content that is not suitable for everyone. Examples: ```text film with sexual violence at a timecode range book with sexual violence at a page range PDF with culturally sensitive content on a page audio with grief or mourning content at a timestamp external work with colonial violence in a chapter ``` The system uses the term `content advisory` internally. The user-facing UI may use: ```text content advisory content warning trigger warning cultural advisory cultural protocol audience suitability ``` The database/system name must not use `trigger` alone, because it can be confused with database triggers. --- ## 10. External work decision External and foreign media are first-class reference targets. Canonical table: ```text uckkarchive_external_work ``` External works represent works not produced by UCKK that may be referenced, taught, reviewed, tagged, or connected to archive/media records. External work types include: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External work rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` --- ## 11. Media source decision Every media object must be able to describe its source. Canonical table: ```text uckkarchive_media_source ``` Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Source rules: ```text Source describes origin and rights context. Source does not grant access by itself. Source does not override content advisory, cultural protocol, visibility, or retention policy. ``` --- ## 12. Archive and media relationship Archive items and media objects are separate but connected. A media object can be linked to one or more archive items. An archive item can reference one or more media objects. The relationship is represented through the media relation and archive relation model, not through duplicated files. Canonical media relation examples: ```text belongs_to_item belongs_to_kristal belongs_to_collection is_derivative_of is_translation_of is_excerpt_of is_proof_for is_source_for replaces references duplicates references_external_work contains_content_marker ``` Relations describe meaning. Relations do not transfer ownership to external plugins or external rights holders. --- ## 13. Database decision Required archive tables: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export ``` Required media library tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` Required content advisory and external-work tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Identifier rule: ```text id = local Moodle database primary key uuid = stable portable object identity ``` UUID rule: ```text Archive objects, media objects, content markers, external works, and export packages use UUIDs for export, restore, duplication, and cross-site portability. ``` --- ## 14. File storage decision All files are stored through Moodle File API. Component: ```text mod_uckkarchive ``` Canonical archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Canonical content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File-area rule: ```text classes/local/file_area_registry.php is the central file-area registry. All controllers, services, pluginfile handling, privacy provider, backup, restore, and tests use the registry. ``` Forbidden storage: ```text No production archive/media files in unmanaged public folders. No binary media files directly in custom database fields. No direct public file URLs as authority. ``` --- ## 15. Capability decision Archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Capability rules: ```text Capabilities are gates, not full authority. Policy classes enforce context, ownership, visibility, status, validation state, restricted state, content advisory rules, cultural protocol rules, retention, and redaction. ``` Removed capability: ```text mod/uckkarchive:versionitem = not used ``` Versioning permissions: ```text archive item revision = mod/uckkarchive:reviseitem media versioning = mod/uckkarchive:versionmedia ``` --- ## 16. Policy architecture decision Policy must be centralized. Archive policy belongs in: ```text classes/local/archive_policy.php ``` Media policy belongs in: ```text classes/local/media_policy.php ``` Content advisory policy belongs in: ```text classes/local/content_policy.php ``` Policy classes enforce: ```text context access capability gates ownership visibility media status archive item status validation state restricted state download authority export authority privacy policy retention policy redaction policy content advisory policy cultural protocol policy audience suitability rules workflow rules ``` Controllers, AMD modules, templates, output classes, and forms must not duplicate policy decisions. --- ## 17. Media lifecycle decision Canonical media states: ```text draft submitted active restricted superseded archived deleted_soft ``` Media lifecycle rule: ```text File existence is not media availability. Media status controls usability. Visibility controls access. Policy controls download and export. Content advisories describe suitability, cultural protocol, and access conditions. Retention controls deletion. ``` --- ## 18. Archive lifecycle decision Canonical archive item statuses: ```text draft submitted under_review validated published restricted contested invalidated superseded archived ``` Canonical validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Validation rule: ```text Validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. ``` --- ## 19. Visibility decision Canonical visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Compatibility rule: ```text institutional must normalize to institution. ``` Visibility rule: ```text Visibility controls who may see the record. Capability controls whether the user may attempt the action. Policy resolves final access. ``` --- ## 20. Content advisory vocabulary decision Content advisory tag examples: ```text sexual_violence violence racism colonial_violence death self_harm substance_use nudity explicit_language culturally_sensitive sacred_content ceremonial_content restricted_knowledge grief_or_mourning requires_context not_for_children ``` Cultural protocol tag examples: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Audience suitability values: ```text general guided mature restricted restricted_cultural restricted_integrity staff_only ``` Content advisory severity values: ```text notice moderate strong restricted ``` Content advisory review states: ```text draft pending_review reviewed approved contested retired ``` Content tag set rule: ```text uckkarchive_content_tag_set groups advisory tags into reusable vocabularies. Examples: general_advisories, cultural_protocols, classroom_suitability, integrity_sensitive, youth_access. ``` Content review rule: ```text uckkarchive_content_review records human review of content markers, advisory tags, cultural protocol notes, suitability, and restriction decisions. AI may suggest tags or markers, but human review is required before advisory status becomes approved. ``` --- ## 21. Content marker and locator decision Canonical content marker table: ```text uckkarchive_content_marker ``` Content marker purpose: ```text Link a content advisory or cultural protocol tag to a precise location inside an internal media object, archive item, media version, external work, or manual reference. ``` Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Canonical locator examples: ```text Movie Maïna -> sexual_violence -> 01:12:30-01:15:10 Book The Body Keeps the Score -> sexual_violence -> page 42-45 PDF -> culturally_sensitive -> page 7 Audio -> grief_or_mourning -> 00:08:12-00:09:40 Website -> colonial_violence -> url_fragment #section-3 ``` Content marker rule: ```text A content marker can point to internal media, archive items, media versions, external works, or manual references. A content marker must include enough locator information to be useful without storing unauthorized copies of external content. ``` --- ## 22. Provenance decision Every meaningful archive, media, content marker, content review, and external work reference must preserve provenance. Canonical provenance values: ```text human ai_assisted imported system archive assembly challenge integrity media external_work content_review ``` Provenance rule: ```text Provenance explains origin. Provenance does not grant authority by itself. ``` Media and archive provenance must support: ```text source description source component source identifier creation actor modification actor validation actor review actor file hash manifest reference import metadata AI-assistance flag external work reference content review reference ``` --- ## 23. Export decision Exports are portable and explainable. Every archive/media export package contains a manifest. Canonical manifest filename: ```text manifest.json ``` Manifest includes: ```text plugin component archive id export id export timestamp export actor export reason archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Export rule: ```text Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` --- ## 24. Documentation decision The documentation set describes the final target behavior. Documentation must not keep a historical gap register. Documentation must not include process-only acceptance checklists. Documentation must not describe the old media-as-attachment model as an active option. The architecture documents are written so AI can generate code from them in separate conversations while remaining aligned through shared variables. --- ## 25. Final architecture rule ```text mod_uckkarchive is a self-contained archive, media-library, and content-advisory Moodle activity module. It owns archive records, media records, media versions, collections, relations, tags, content advisories, cultural protocol notes, external work references, proofs, Kristals, provenance, revisions, validation state, restricted metadata, export packages, and export manifests. It uses Moodle for plugin lifecycle, contexts, users, capabilities, File API, Privacy API, Backup/Restore API, events, settings, language, rendering, scheduled tasks, and external services. The module is modular enough to troubleshoot independently and to duplicate for future archive/media/content-advisory use cases without becoming detached from Moodle. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/02_domain_boundaries.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 1de279e95e3bbfbfa9041030c0466e2b943fd71962638500bf5003ef24967811 CONTENT_BYTES: 19942 ================================================================================================ # 02 — Domain Boundaries **Path:** `docs/02_domain_boundaries.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Domain ownership boundaries for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle module. --- ## 1. Purpose This document defines the domain boundaries of `mod_uckkarchive`. `mod_uckkarchive` is responsible for archive memory, media-library management, content advisories, cultural sensitivity markers, external work references, provenance, revision history, validation state, restricted archive metadata, and archive/media exports. This document defines what the module owns, what it may reference, and what it must not become. --- ## 2. Core boundary rule Canonical formula: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` `mod_uckkarchive` owns its internal archive, media, and content advisory domains. It does not own external Moodle or UCKK authority domains. Preservation does not transfer authority. Reference does not transfer authority. Export does not transfer authority. --- ## 3. Domain ownership map ```text GRADE_OWNER = Moodle gradebook REGISTRY_OWNER = local_uckk CHALLENGE_OWNER = mod_uckkchallenge ASSEMBLY_OWNER = mod_uckkassembly INTEGRITY_OWNER = tool_uckkintegrity REPORT_OWNER = report_uckk ARCHIVE_OWNER = mod_uckkarchive ``` Ownership rule: ```text The plugin that owns a workflow remains the authority for that workflow. mod_uckkarchive may preserve evidence, media, summaries, exports, provenance, and snapshots from other workflows. mod_uckkarchive must not become the workflow authority for those external domains. ``` --- ## 4. What `mod_uckkarchive` owns `mod_uckkarchive` owns: ```text archive records archive items media records media versions media files media collections media collection membership media relations media tags proof records Kristals provenance records revision history validation state restricted archive metadata restricted media metadata content advisory tags cultural sensitivity tags content tag sets content markers content reviews external works foreign media references media source records audience suitability rules export packages export manifests ``` `mod_uckkarchive` owns the following internal engines: ```text archive engine media library engine content advisory engine provenance engine revision engine validation engine export engine ``` --- ## 5. What `mod_uckkarchive` does not own `mod_uckkarchive` does not own: ```text grades gradebook records official transcripts course enrolment authority site-wide user identity authority global UCKK registry records challenge workflow state Assembly decision authority integrity case procedure state institutional reporting authority external work copyright ownership external work publication rights ``` The module may preserve or reference records from these domains, but it does not become their authority. --- ## 6. Moodle platform boundary `mod_uckkarchive` uses Moodle for: ```text plugin lifecycle course module context course visibility users roles capabilities groups File API Privacy API Backup API Restore API External Services API events settings language strings rendering scheduled tasks ``` Moodle platform boundary rule: ```text mod_uckkarchive must not bypass Moodle contexts. mod_uckkarchive must not bypass Moodle capabilities. mod_uckkarchive must not bypass Moodle File API. mod_uckkarchive must not bypass Moodle Privacy API. mod_uckkarchive must not bypass Moodle Backup/Restore API. mod_uckkarchive must not bypass Moodle External Services API. ``` --- ## 7. Gradebook boundary Moodle gradebook owns: ```text grades grade items grade history final marks assessment scores official transcript-relevant results ``` `mod_uckkarchive` may own: ```text proof records media evidence archive evidence portfolio evidence validation notes exported evidence packages ``` Boundary rule: ```text Archive evidence is not a grade. Validation is not a grade. Media completion is not a grade unless Moodle gradebook receives a grade through proper Moodle APIs. ``` `mod_uckkarchive` must not write arbitrary gradebook records as archive state. --- ## 8. Registry boundary `local_uckk` owns: ```text UCKK registry records institutional configuration program structures global UCKK profiles cross-plugin identity mapping shared UCKK configuration ``` `mod_uckkarchive` may reference: ```text program ids course ids cohort ids institutional labels registry-derived display metadata ``` Boundary rule: ```text Registry data may contextualize archive records. Registry data remains owned by local_uckk. ``` --- ## 9. Course boundary Moodle course and course module context own: ```text course membership course visibility course roles course groups course module visibility completion framework ``` `mod_uckkarchive` owns: ```text archive activity instance archive item records media library records inside the activity context content advisories linked to archive/media records proof records Kristals provenance revision history validation state exports ``` Boundary rule: ```text Course context controls where the module lives. The archive/media module controls its internal records. ``` --- ## 10. Challenge boundary `mod_uckkchallenge` owns: ```text challenge workflow challenge state challenge rules challenge submissions challenge evaluation process challenge result authority ``` `mod_uckkarchive` may preserve: ```text challenge evidence challenge media challenge proof packages challenge provenance challenge snapshots challenge-related content advisories challenge-related export packages ``` Boundary rule: ```text Archive proof is not the challenge workflow. Archive preservation does not decide challenge outcome. ``` --- ## 11. Assembly boundary `mod_uckkassembly` owns: ```text motions deliberations votes minutes workflow decision workflow Assembly authority final Assembly decisions ``` `mod_uckkarchive` may preserve: ```text Assembly minutes snapshots decision snapshots attachments minority reports supporting media public decision packages restricted decision records content advisories for Assembly materials export packages ``` Boundary rule: ```text The archive preserves Assembly memory. The Assembly remains the decision authority. ``` --- ## 12. Integrity boundary `tool_uckkintegrity` owns: ```text integrity case workflow case participants findings sanctions appeals closure restricted procedure state ``` `tool_uckkintegrity` is an optional integration. Ordinary archive, media, and content advisory operation must not require `tool_uckkintegrity`. `mod_uckkarchive` may preserve: ```text integrity evidence restricted proof files restricted media case-linked archive records integrity export packages restricted content advisories provenance records redacted summaries ``` Boundary rule: ```text The archive may preserve integrity evidence. The archive does not decide integrity cases. Integrity-specific archive features must be hidden, disabled, or fail closed when tool_uckkintegrity is absent. ``` --- ## 13. Reporting boundary `report_uckk` owns: ```text institutional dashboards institutional reports cross-course reports cross-plugin reports cohort reports program reports administrative reporting exports ``` `mod_uckkarchive` owns: ```text archive export packages media export packages collection export packages manifest.json files archive/media provenance bundles permission-filtered archive export payloads ``` Boundary rule: ```text Archive exports preserve archive/media records. Reports present institutional views. Archive export is not institutional reporting authority. ``` --- ## 14. External work boundary `mod_uckkarchive` may reference external works. External works include: ```text film book article podcast website external video external image public archive item third-party PDF other ``` Canonical external work table: ```text uckkarchive_external_work ``` External/foreign media boundary rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. The archive must not store unauthorized copies of external works. ``` --- ## 15. Media source boundary Canonical media source table: ```text uckkarchive_media_source ``` Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Media source boundary rule: ```text Media source describes origin and rights context. Media source does not grant access by itself. Media source does not override policy, visibility, retention, redaction, or cultural protocol rules. ``` --- ## 16. Content advisory boundary `mod_uckkarchive` owns a content advisory subsystem. Canonical subsystem name: ```text content advisories, cultural sensitivity tags, content markers, external works, reviews, and audience suitability rules ``` Required tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Content advisory boundary rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` A content advisory may affect: ```text display warnings teaching context audience suitability access prompts restricted visibility cultural protocol review export filtering review workflow redaction decisions ``` A content advisory must not silently delete or hide records without policy. --- ## 17. Cultural protocol boundary Cultural protocol data may include: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Cultural protocol boundary rule: ```text Cultural protocol rules are access and context rules. They do not become external ownership authority. They must be enforced through module policy before display, download, export, or reuse. ``` --- ## 18. Content marker boundary Canonical content marker table: ```text uckkarchive_content_marker ``` A content marker may point to: ```text archive item media object media version external work manual reference ``` Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Content marker boundary rule: ```text A content marker locates advisory meaning. A content marker does not copy external content. A content marker does not transfer external rights. ``` --- ## 19. Content review boundary Canonical content review table: ```text uckkarchive_content_review ``` Content review states: ```text draft pending_review reviewed approved contested retired ``` Content review boundary rule: ```text AI may suggest tags or markers. Human review is required before advisory status becomes approved. AI cannot approve cultural protocol access. AI cannot remove cultural restrictions. ``` --- ## 20. Content tag set boundary Canonical content tag set table: ```text uckkarchive_content_tag_set ``` Content tag sets group reusable vocabularies. Examples: ```text general_advisories cultural_protocols classroom_suitability integrity_sensitive youth_access ``` Content tag set boundary rule: ```text Tag sets organize advisory vocabulary. Tag sets do not decide access alone. Access decisions belong to policy classes. ``` --- ## 21. AI assistance boundary AI may assist with: ```text metadata suggestions content advisory suggestions content marker suggestions summary drafts classification drafts transcript drafts caption drafts search enhancement ``` AI must not: ```text validate archive records invalidate archive records approve content reviews approve cultural protocol access remove cultural restrictions decide grade outcomes decide integrity outcomes decide Assembly outcomes override human review ``` AI boundary rule: ```text AI assistance is provenance. AI assistance is not authority. ``` --- ## 22. File API boundary All files belong to Moodle File API. Component: ```text mod_uckkarchive ``` Canonical archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Canonical content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File API boundary rule: ```text File areas are declared centrally in classes/local/file_area_registry.php. All controllers, services, pluginfile handling, privacy provider, backup, restore, and tests use the registry. No production archive/media files live in unmanaged public folders. ``` --- ## 23. Privacy boundary `mod_uckkarchive` owns privacy responsibilities for personal data stored in its own tables and file areas. Privacy scope includes: ```text archive items proofs Kristals provenance revisions exports media objects media versions media collections media relations media tags content advisories content markers content reviews external work references media source records user-linked files restricted metadata ``` Privacy boundary rule: ```text Privacy API behavior belongs to mod_uckkarchive for records stored by mod_uckkarchive. External authority records remain outside the archive privacy surface unless copied into archive-owned records. ``` --- ## 24. Backup and restore boundary Backup includes module-owned records. Restore reconstructs module-owned records. Backup/restore scope includes: ```text activity instance archive items proofs Kristals provenance revisions exports media objects media versions media files media collections media relations media tags content tags content tag sets content markers content reviews external works media source records file areas manifest records ``` Backup/restore boundary rule: ```text Restore must not create grades. Restore must not create external workflow authority. Restore must not turn external work references into owned media. Restore must not make restricted or culturally restricted records public. ``` --- ## 25. Export boundary `mod_uckkarchive` owns archive/media export packages. Canonical manifest filename: ```text manifest.json ``` Exports may include: ```text archive records media records media versions file hashes media files when permitted collections relations tags content advisories content markers content reviews external work metadata provenance revision history validation state redaction state restricted flags ``` Export boundary rule: ```text Exports are portable and explainable. Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` --- ## 26. Capability boundary Capabilities are gates. Canonical archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Canonical media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Canonical content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Capability boundary rule: ```text Capabilities do not replace policy. Policy classes enforce context, ownership, visibility, status, validation state, restricted state, content advisory rules, cultural protocol rules, retention, and redaction. ``` Removed capability: ```text mod/uckkarchive:versionitem = not used ``` --- ## 27. Policy class boundary Archive policy belongs in: ```text classes/local/archive_policy.php ``` Media policy belongs in: ```text classes/local/media_policy.php ``` Content advisory policy belongs in: ```text classes/local/content_policy.php ``` Policy classes enforce: ```text context access capability gates ownership visibility media status archive item status validation state restricted state content advisory rules cultural protocol rules download authority export authority privacy policy retention policy redaction policy workflow rules ``` Policy boundary rule: ```text Controllers coordinate. Services expose contracts. Forms collect input. Output classes format data. Templates render. AMD modules provide UI behavior. Policy classes decide authority. ``` --- ## 28. Database boundary Required archive tables: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export ``` Required media library tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` Required content advisory and external-work tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Identifier rule: ```text id = local Moodle database primary key uuid = stable portable object identity ``` Database boundary rule: ```text The database stores module-owned records. The database does not store binary media content directly in custom fields. The database does not duplicate external workflow authority. ``` --- ## 29. Duplication and portability boundary The module is designed to be self-contained enough to be duplicated for other archive/media use cases. Portable identity relies on: ```text uuid manifest.json file hashes media version UUIDs external work UUIDs content marker UUIDs collection UUIDs provenance records ``` Duplication boundary rule: ```text Duplication copies archive/media module records. Duplication must not copy external authority as if it were owned by the archive. ``` --- ## 30. Final boundary rule ```text mod_uckkarchive owns archive memory, media library objects, content advisories, cultural protocol metadata, external work references, provenance, revisions, validation state, restricted metadata, and export packages. It uses Moodle for context, users, roles, capabilities, files, privacy, backup, restore, services, events, settings, language, rendering, and scheduled tasks. It does not own grades, transcripts, enrolments, registry authority, challenge workflow, Assembly authority, integrity case authority, institutional reporting authority, or external copyright ownership. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/03_file_architecture.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: c21d2f7b5ec5a8f3644bf604243a72f37e89f966161ea4e41712036768ba6d97 CONTENT_BYTES: 28778 ================================================================================================ # 03 — File Architecture **Path:** `docs/03_file_architecture.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Complete file and folder architecture for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Purpose This document defines the final file architecture for `mod_uckkarchive`. The module is: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` The file architecture must support: ```text archive memory media library management content advisories cultural sensitivity tags content markers external works foreign media references proof records Kristals provenance revision history validation restricted metadata exports backup/restore privacy testing ``` This document is descriptive. It defines the final target structure to code. It is not a historical document, gap register, release note, or acceptance checklist. --- ## 2. Canonical plugin paths Canonical Moodle path: ```text mod/uckkarchive ``` Active Moodle path: ```text C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive ``` Source repository path: ```text C:\mycode\UCKK\uckk-moodle\mod\uckkarchive ``` Documentation path: ```text mod/uckkarchive/docs ``` Moodle component: ```text mod_uckkarchive ``` Plugin type: ```text mod ``` Plugin folder: ```text uckkarchive ``` --- ## 3. Top-level folder architecture ```text mod/uckkarchive/ ├── add.php ├── export.php ├── index.php ├── item.php ├── lib.php ├── locallib.php ├── media.php ├── mod_form.php ├── settings.php ├── styles.css ├── validate.php ├── version.php ├── view.php ├── amd/ ├── backup/ ├── classes/ ├── db/ ├── docs/ ├── lang/ ├── pix/ ├── templates/ └── tests/ ``` Top-level rule: ```text Root PHP files coordinate HTTP requests and Moodle entry points. Business authority belongs in classes/local. External service contracts belong in classes/external. Renderable data belongs in classes/output. Templates render pre-filtered data. AMD modules provide client-side behavior only. ``` --- ## 4. Root PHP files ```text add.php export.php index.php item.php lib.php locallib.php media.php mod_form.php settings.php validate.php version.php view.php ``` | File | Role | |---|---| | `add.php` | Controller for adding archive items, media references, proof records, or draft archive material. | | `export.php` | Controller for export preview, export request, export download flow, and export status display. | | `index.php` | Moodle course-level index page for all `uckkarchive` activities in a course. | | `item.php` | Controller for a single archive item, including item view, item panels, media links, provenance, and validation display. | | `lib.php` | Moodle module callbacks, pluginfile handler, navigation integration, feature declarations, deletion hooks, and core plugin callbacks. | | `locallib.php` | Procedural helper compatibility layer. New domain logic belongs in `classes/local`. | | `media.php` | Controller for the media library page, media browsing, media collection browsing, and media-management entry points. | | `mod_form.php` | Moodle activity instance configuration form. | | `settings.php` | Moodle site administration settings for the plugin. | | `validate.php` | Controller for validation, revision, contestation, restriction, and review flows. | | `version.php` | Moodle plugin version, maturity, release, component, and dependency metadata. | | `view.php` | Main activity view controller. | Controller rule: ```text Controllers do not own policy. Controllers resolve request context and delegate to classes/local, classes/form, classes/output, and external service contracts. ``` --- ## 5. Root asset files ```text styles.css ``` | File | Role | |---|---| | `styles.css` | Plugin CSS for archive, media library, cards, panels, advisory badges, restricted markers, validation states, and collections. | CSS rule: ```text CSS must not hide restricted data as a security mechanism. Restricted data must be filtered server-side before rendering. ``` --- ## 6. AMD source files ```text amd/src/archive.js amd/src/content_advisory.js amd/src/export.js amd/src/external_work.js amd/src/kristal.js amd/src/media.js amd/src/media_collection.js ``` | File | Role | |---|---| | `amd/src/archive.js` | Archive item list interactions, filtering, archive item cards, item panels, and archive UI refresh. | | `amd/src/content_advisory.js` | Content advisory panel interactions, marker UI, advisory badges, suitability display, and reviewer UI behavior. | | `amd/src/export.js` | Export preview, export option UI, export progress, export status, and export action wiring. | | `amd/src/external_work.js` | External work lookup, reference display, work-card refresh, and locator UI behavior. | | `amd/src/kristal.js` | Kristal card interactions, Kristal edit UI, and Kristal-specific service calls. | | `amd/src/media.js` | Media library browsing, media upload UI, media cards, previews, thumbnails, filtering, and media metadata editing. | | `amd/src/media_collection.js` | Media collection creation, ordering, membership editing, and collection view interactions. | AMD source rule: ```text AMD source files drive UI behavior. They do not authorize access. They do not decide validation, restriction, redaction, cultural protocol, or export permission. ``` --- ## 7. AMD build files ```text amd/build/archive.min.js amd/build/content_advisory.min.js amd/build/export.min.js amd/build/external_work.min.js amd/build/kristal.min.js amd/build/media.min.js amd/build/media_collection.min.js ``` Build rule: ```text amd/src/* is the source of truth. amd/build/* is generated for Moodle runtime. Generated AMD files are not edited manually. ``` --- ## 8. Backup and restore files ```text backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` | File | Role | |---|---| | `backup/moodle2/backup_uckkarchive_activity_task.class.php` | Moodle backup task class. Registers backup steps, file areas, and encoded links. | | `backup/moodle2/backup_uckkarchive_stepslib.php` | Backup structure for activity, archive items, media objects, media versions, collections, tags, relations, content advisories, external works, proofs, Kristals, provenance, revisions, exports, files, and metadata. | | `backup/moodle2/restore_uckkarchive_activity_task.class.php` | Moodle restore task class. Registers restore steps and link decoding. | | `backup/moodle2/restore_uckkarchive_stepslib.php` | Restore implementation for records, remapped IDs, restored UUIDs, files, relations, collections, advisories, and external references. | Backup/restore rule: ```text Backup preserves module-owned archive/media/content-advisory state. Restore reconstructs module-owned records only. Restore does not create gradebook authority, Assembly authority, integrity case authority, or report authority. ``` --- ## 9. Completion files ```text classes/completion/custom_completion.php ``` | File | Role | |---|---| | `classes/completion/custom_completion.php` | Custom Moodle completion logic for viewing, submitting, revising, validating, or interacting with archive/media records. | --- ## 10. Event classes ```text classes/event/archive_viewed.php classes/event/archive_item_created.php classes/event/archive_item_validated.php classes/event/archive_item_revised.php classes/event/archive_item_exported.php classes/event/media_created.php classes/event/media_updated.php classes/event/media_version_created.php classes/event/media_collection_created.php classes/event/media_exported.php classes/event/content_marker_created.php classes/event/content_marker_reviewed.php classes/event/external_work_created.php ``` | File | Role | |---|---| | `classes/event/archive_viewed.php` | Fired when an archive activity or archive view is viewed. | | `classes/event/archive_item_created.php` | Fired when an archive item is created. | | `classes/event/archive_item_validated.php` | Fired when an archive item validation state changes. | | `classes/event/archive_item_revised.php` | Fired when an archive item revision is created. | | `classes/event/archive_item_exported.php` | Fired when archive material is exported. | | `classes/event/media_created.php` | Fired when a media object is created. | | `classes/event/media_updated.php` | Fired when media metadata or lifecycle state changes. | | `classes/event/media_version_created.php` | Fired when a media version is created. | | `classes/event/media_collection_created.php` | Fired when a media collection is created. | | `classes/event/media_exported.php` | Fired when media is exported. | | `classes/event/content_marker_created.php` | Fired when a content marker/advisory locator is created. | | `classes/event/content_marker_reviewed.php` | Fired when a content marker or content advisory is reviewed. | | `classes/event/external_work_created.php` | Fired when an external work reference is created. | Event rule: ```text Events record successful state changes. Events must not expose restricted content, raw media, private notes, culturally restricted details, or redacted data. ``` --- ## 11. External service files — archive ```text classes/external/get_archive.php classes/external/get_archive_items.php classes/external/get_archive_item.php classes/external/get_archive_item_card.php classes/external/get_proofs.php classes/external/get_provenance_panel.php classes/external/get_kristal.php classes/external/get_revisions.php classes/external/get_restricted_item.php classes/external/save_item_draft.php classes/external/add_item.php classes/external/add_proof.php classes/external/update_provenance.php classes/external/validate_item.php classes/external/revise_item.php classes/external/create_kristal.php classes/external/update_kristal.php ``` Archive service rule: ```text Archive services check context, capability, ownership, visibility, validation state, restricted state, provenance, redaction, and workflow policy. ``` --- ## 12. External service files — media library ```text classes/external/get_media.php classes/external/get_media_item.php classes/external/get_media_card.php classes/external/search_media.php classes/external/add_media.php classes/external/update_media.php classes/external/delete_media.php classes/external/add_media_version.php classes/external/get_media_versions.php classes/external/get_media_relations.php classes/external/add_media_relation.php classes/external/remove_media_relation.php classes/external/get_media_collections.php classes/external/get_media_collection.php classes/external/add_media_collection.php classes/external/update_media_collection.php classes/external/add_media_to_collection.php classes/external/remove_media_from_collection.php classes/external/tag_media.php classes/external/untag_media.php ``` Media service rule: ```text Media services check media policy, media status, file access, ownership, collection membership, relation validity, download authority, export authority, and restricted media access. ``` --- ## 13. External service files — content advisories and external works ```text classes/external/get_content_tags.php classes/external/get_content_tag_sets.php classes/external/get_content_markers.php classes/external/add_content_marker.php classes/external/update_content_marker.php classes/external/delete_content_marker.php classes/external/review_content_marker.php classes/external/get_external_works.php classes/external/get_external_work.php classes/external/add_external_work.php classes/external/update_external_work.php ``` Content advisory service rule: ```text Content advisory services check context, capability, visibility, cultural protocol restrictions, review state, redaction, and suitability rules. ``` --- ## 14. External service files — exports ```text classes/external/get_export_preview.php classes/external/export_items.php classes/external/export_media.php classes/external/export_collection.php classes/external/get_export_status.php ``` Export service rule: ```text Export services generate permission-filtered, redaction-aware, culturally aware, manifest-backed export packages. ``` --- ## 15. Form files ```text classes/form/archive_item_form.php classes/form/content_marker_form.php classes/form/content_review_form.php classes/form/content_tag_form.php classes/form/export_form.php classes/form/external_work_form.php classes/form/kristal_form.php classes/form/media_collection_form.php classes/form/media_form.php classes/form/media_relation_form.php classes/form/media_version_form.php classes/form/validation_form.php ``` | File | Role | |---|---| | `classes/form/archive_item_form.php` | Archive item create/edit form. | | `classes/form/content_marker_form.php` | Content marker/advisory locator form. | | `classes/form/content_review_form.php` | Human review form for content markers and cultural protocol notes. | | `classes/form/content_tag_form.php` | Content advisory and cultural tag form. | | `classes/form/export_form.php` | Archive/media export options form. | | `classes/form/external_work_form.php` | External/foreign work reference form. | | `classes/form/kristal_form.php` | Kristal create/edit form. | | `classes/form/media_collection_form.php` | Media collection create/edit form. | | `classes/form/media_form.php` | Media object create/edit/upload form. | | `classes/form/media_relation_form.php` | Media relation create/edit form. | | `classes/form/media_version_form.php` | Media version upload/edit form. | | `classes/form/validation_form.php` | Archive validation, revision, restriction, and contestation form. | Form rule: ```text Forms collect and shape input. Policy remains in classes/local. ``` --- ## 16. Local domain files — archive ```text classes/local/archive_item.php classes/local/archive_policy.php classes/local/export_package.php classes/local/kristal.php classes/local/proof.php classes/local/provenance.php classes/local/revision.php ``` | File | Role | |---|---| | `classes/local/archive_item.php` | Archive item domain logic. | | `classes/local/archive_policy.php` | Archive policy for access, visibility, validation, restriction, revision, and export. | | `classes/local/export_package.php` | Export package creation, manifest generation, and export file coordination. | | `classes/local/kristal.php` | Kristal domain logic. | | `classes/local/proof.php` | Proof record domain logic. | | `classes/local/provenance.php` | Provenance and provenance hash logic. | | `classes/local/revision.php` | Archive revision and version history logic. | --- ## 17. Local domain files — media ```text classes/local/media.php classes/local/media_collection.php classes/local/media_file.php classes/local/media_policy.php classes/local/media_relation.php classes/local/media_search.php classes/local/media_source.php classes/local/media_tag.php classes/local/media_version.php ``` | File | Role | |---|---| | `classes/local/media.php` | Media object domain logic. | | `classes/local/media_collection.php` | Media collection logic. | | `classes/local/media_file.php` | Moodle File API coordination for media file areas. | | `classes/local/media_policy.php` | Media access, download, edit, versioning, export, and restriction policy. | | `classes/local/media_relation.php` | Media relation graph logic. | | `classes/local/media_search.php` | Media search/filter logic. | | `classes/local/media_source.php` | Media source and ownership classification logic. | | `classes/local/media_tag.php` | Media tag logic. | | `classes/local/media_version.php` | Media versioning logic. | --- ## 18. Local domain files — content advisory and external work ```text classes/local/content_marker.php classes/local/content_policy.php classes/local/content_review.php classes/local/content_tag.php classes/local/content_tag_set.php classes/local/external_work.php ``` | File | Role | |---|---| | `classes/local/content_marker.php` | Content advisory locator logic for timecodes, pages, scenes, sections, and manual references. | | `classes/local/content_policy.php` | Content advisory, cultural protocol, suitability, and restricted-cultural access policy. | | `classes/local/content_review.php` | Human review workflow for content markers, advisory tags, suitability, and cultural protocol notes. | | `classes/local/content_tag.php` | Content advisory and cultural sensitivity tag logic. | | `classes/local/content_tag_set.php` | Reusable tag-set vocabulary logic. | | `classes/local/external_work.php` | External/foreign media and third-party work reference logic. | --- ## 19. Local infrastructure files ```text classes/local/context_resolver.php classes/local/file_area_registry.php classes/local/manifest_builder.php classes/local/metadata_validator.php classes/local/uuid.php ``` | File | Role | |---|---| | `classes/local/context_resolver.php` | Central context, course, cm, archive, item, and media resolution. | | `classes/local/file_area_registry.php` | Single source of truth for all archive, media, and content-advisory file areas. | | `classes/local/manifest_builder.php` | Export manifest builder for archive/media/content advisory packages. | | `classes/local/metadata_validator.php` | JSON metadata validation and normalization. | | `classes/local/uuid.php` | Stable UUID generation, validation, and normalization. | Local rule: ```text classes/local is the authority layer for archive, media, content advisory, external work, and export behavior. ``` --- ## 20. Output files ```text classes/output/archive_item_card.php classes/output/archive_view.php classes/output/content_advisory_panel.php classes/output/external_work_card.php classes/output/kristal_card.php classes/output/media_card.php classes/output/media_collection.php classes/output/media_library.php classes/output/media_version_list.php classes/output/provenance_panel.php classes/output/renderer.php ``` | File | Role | |---|---| | `classes/output/archive_item_card.php` | Renderable archive item card data. | | `classes/output/archive_view.php` | Main archive view renderable data. | | `classes/output/content_advisory_panel.php` | Renderable content advisory panel data. | | `classes/output/external_work_card.php` | Renderable external work reference card data. | | `classes/output/kristal_card.php` | Renderable Kristal card data. | | `classes/output/media_card.php` | Renderable media card data. | | `classes/output/media_collection.php` | Renderable media collection data. | | `classes/output/media_library.php` | Renderable media library page data. | | `classes/output/media_version_list.php` | Renderable media version list data. | | `classes/output/provenance_panel.php` | Renderable provenance panel data. | | `classes/output/renderer.php` | Moodle renderer for module templates. | Output rule: ```text Output classes prepare already-authorized data for templates. Output classes do not grant access. ``` --- ## 21. Privacy files ```text classes/privacy/provider.php ``` Privacy provider covers: ```text archive items proofs Kristals provenance revisions exports media objects media versions media collections media relations media tags media sources content tags content tag sets content markers content reviews external works user-linked files restricted metadata culturally restricted metadata ``` Privacy rule: ```text Privacy API behavior belongs to mod_uckkarchive for all records stored by mod_uckkarchive. ``` --- ## 22. Observer and scheduled task files ```text classes/observer.php classes/task/generate_archive_exports.php classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/purge_expired_exports.php classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php classes/task/validate_pending_items.php ``` | File | Role | |---|---| | `classes/observer.php` | Moodle event observer handlers. | | `classes/task/generate_archive_exports.php` | Queued archive export generation. | | `classes/task/generate_media_derivatives.php` | Queued media derivative generation. | | `classes/task/generate_media_thumbnails.php` | Queued thumbnail generation. | | `classes/task/purge_expired_exports.php` | Export retention cleanup. | | `classes/task/rebuild_media_search.php` | Media search/index maintenance. | | `classes/task/rebuild_content_marker_index.php` | Content marker and advisory locator index maintenance. | | `classes/task/validate_pending_items.php` | Scheduled validation/maintenance helper. | Task rule: ```text Scheduled tasks reuse classes/local domain logic. Scheduled tasks do not bypass policy checks for generated outputs. ``` --- ## 23. Database files ```text db/access.php db/events.php db/install.xml db/services.php db/tasks.php db/upgrade.php ``` | File | Role | |---|---| | `db/access.php` | Moodle capability definitions. | | `db/events.php` | Moodle observer declarations. | | `db/install.xml` | Full current target database schema. | | `db/services.php` | External service declarations. | | `db/tasks.php` | Scheduled task declarations. | | `db/upgrade.php` | Schema and data migration logic. | Database file rule: ```text db/install.xml defines the current target schema. db/upgrade.php migrates existing installs to the current target schema. ``` --- ## 24. Language files ```text lang/en/uckkarchive.php lang/fr/uckkarchive.php ``` Language files contain strings for: ```text plugin identity capabilities settings forms services events archive UI media UI content advisory UI external work UI collections relations versions validation privacy backup/restore errors warnings access messages cultural protocol messages audience suitability messages ``` Language rule: ```text Language files must not contain strings for removed or unused capabilities. English and French language keys must remain aligned. ``` --- ## 25. Template files ```text templates/archive_item_card.mustache templates/archive_view.mustache templates/content_advisory_panel.mustache templates/external_work_card.mustache templates/kristal_card.mustache templates/media_card.mustache templates/media_collection.mustache templates/media_library.mustache templates/media_relation_list.mustache templates/media_upload.mustache templates/media_version_list.mustache templates/proof_card.mustache templates/provenance_panel.mustache templates/validation_panel.mustache ``` Template rule: ```text Templates render permission-filtered data. Templates do not enforce authority, visibility, cultural protocol, restriction, redaction, or download access. ``` --- ## 26. Test files ```text tests/archive_test.php tests/backup_restore_test.php tests/content_advisory_test.php tests/export_test.php tests/external_work_test.php tests/file_api_test.php tests/lib_test.php tests/media_library_test.php tests/privacy_provider_test.php tests/services_test.php tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` | File | Role | |---|---| | `tests/archive_test.php` | Archive domain tests. | | `tests/backup_restore_test.php` | Backup and restore tests. | | `tests/content_advisory_test.php` | Content advisory, tag set, marker, review, and cultural protocol tests. | | `tests/export_test.php` | Archive/media/content advisory export tests. | | `tests/external_work_test.php` | External/foreign work reference tests. | | `tests/file_api_test.php` | File API, pluginfile, file-area, and access tests. | | `tests/lib_test.php` | Moodle callback and helper tests. | | `tests/media_library_test.php` | Media object, version, collection, relation, source, and tag tests. | | `tests/privacy_provider_test.php` | Privacy provider tests. | | `tests/services_test.php` | External service and permission-filtering tests. | | `tests/behat/uckkarchive.feature` | Archive UI behavior tests. | | `tests/behat/uckkarchive_media.feature` | Media library UI behavior tests. | | `tests/behat/uckkarchive_content_advisory.feature` | Content advisory UI behavior tests. | Test rule: ```text Tests verify final target behavior. Tests must not depend on historical gap documents. Tests must not require mod/uckkarchive:versionitem. ``` --- ## 27. Pix assets ```text pix/icon.svg pix/media.svg pix/collection.svg pix/content_advisory.svg pix/external_work.svg ``` | File | Role | |---|---| | `pix/icon.svg` | Main Moodle activity icon. | | `pix/media.svg` | Media library icon. | | `pix/collection.svg` | Media collection icon. | | `pix/content_advisory.svg` | Content advisory icon. | | `pix/external_work.svg` | External work reference icon. | Pix rule: ```text pix contains static plugin interface assets only. User-uploaded media never belongs in pix. ``` --- ## 28. Documentation files ```text docs/_alignment_variables.md docs/00_index.md docs/01_architecture_decision.md docs/02_domain_boundaries.md docs/03_file_architecture.md docs/04_data_model.md docs/05_media_library.md docs/06_file_api_and_storage.md docs/07_permissions_and_roles.md docs/08_archive_workflows.md docs/09_media_workflows.md docs/10_provenance_versioning_validation.md docs/11_privacy_retention_redaction.md docs/12_backup_restore.md docs/13_services_and_ajax_api.md docs/14_events_and_audit.md docs/15_ui_templates_and_amd.md docs/16_integration_with_courses.md docs/17_integration_with_challenges.md docs/18_integration_with_assemblies.md docs/19_integration_with_integrity.md docs/20_reporting_and_exports.md docs/21_testing_strategy.md docs/22_installation.md docs/23_upgrade.md docs/24_release_spec.md ``` Documentation rule: ```text Documentation describes final target behavior. Documentation does not keep historical gap registers. Documentation does not contain acceptance-checklist process files. Documentation does not contain release-note process files. ``` --- ## 29. Required database tables supported by this architecture Archive tables: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export ``` Media tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` Content advisory and external-work tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Identifier rule: ```text id is the local Moodle database primary key. uuid is the stable portable object identity. ``` --- ## 30. Canonical File API areas supported by this architecture Archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File-area registry rule: ```text classes/local/file_area_registry.php is the single source of truth for file areas. ``` --- ## 31. Non-release files These files are not part of the clean release package: ```text *.bak *.tmp *.orig *.rej *.patch *.log .DS_Store Thumbs.db node_modules/ runtime export files outside Moodle File API codedump files AI scratch files ``` Non-release rule: ```text Generated runtime data belongs in Moodle runtime storage or Moodle File API, not in source control. ``` --- ## 32. Final architecture rule ```text mod_uckkarchive is a self-contained archive, media-library, and content-advisory module. Root files coordinate. classes/local owns authority. classes/external exposes services. classes/output prepares render data. templates render. AMD modules provide UI behavior. db declares schema, capabilities, services, tasks, events, and upgrades. backup/moodle2 preserves and restores module-owned records. lang provides strings. tests verify final target behavior. pix provides static UI assets. docs define the target implementation. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/04_data_model.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 3f849aafbad92aa64bbe47d48b65af96e6b2a4d5093246d26947f5083fea2a67 CONTENT_BYTES: 39262 ================================================================================================ # 04 — Data Model **Path:** `docs/04_data_model.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Database schema, object model, identifiers, relationships, lifecycle values, file-area references, privacy fields, and export identity for the self-contained UCKK Archive, Media Library, and Content Advisory system. --- ## 1. Purpose This document defines the final data model for `mod_uckkarchive`. `mod_uckkarchive` is a Moodle-native activity module with a self-contained internal data model for: ```text archive memory media library management media versioning media collections media relations content advisories cultural sensitivity tags external/foreign media references proof records Kristals provenance revision history validation state restricted metadata export packages export manifests ``` The module stores structured metadata in Moodle database tables and stores files through Moodle File API. The module does not store binary media files directly in custom database fields. --- ## 2. Core data ownership `mod_uckkarchive` owns the following data domains: ```text archive records archive items proof records Kristals provenance records revision records export records media records media versions media relations media tags media collections media collection membership content advisory tags content tag sets content markers content reviews external works media source records ``` `mod_uckkarchive` does not own: ```text grades gradebook records transcripts course enrolment authority administrative registry records challenge workflow authority Assembly decision authority integrity case authority institutional report authority ``` Records from external domains may be referenced or preserved as archive/media evidence, but preservation does not transfer authority. --- ## 3. Identifier model Every primary table uses a Moodle local integer primary key: ```text id ``` Every portable domain object also has a stable UUID: ```text uuid ``` Identifier rule: ```text id = local Moodle database identity uuid = portable object identity ``` Objects requiring UUIDs: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` UUIDs support: ```text backup restore export import duplication cross-site portability manifest generation external references media graph reconstruction ``` --- ## 4. Table list Required archive tables: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export ``` Required media library tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` Required content advisory and external-work tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` --- ## 5. Shared field conventions Most domain tables use these standard fields where applicable: ```text id uuid archiveid courseid cmid contextid userid createdby modifiedby timecreated timemodified status visibility metadata ``` Common meaning: | Field | Meaning | |---|---| | `id` | Moodle local database primary key. | | `uuid` | Stable portable object identity. | | `archiveid` | Parent `uckkarchive` activity instance. | | `courseid` | Moodle course ID. | | `cmid` | Moodle course module ID. | | `contextid` | Moodle context ID. | | `userid` | Primary user associated with the record, when applicable. | | `createdby` | User who created the record. | | `modifiedby` | User who last modified the record. | | `timecreated` | Creation timestamp. | | `timemodified` | Last modification timestamp. | | `status` | Lifecycle state of the object. | | `visibility` | Visibility/access classification. | | `metadata` | JSON metadata for extensible non-authority fields. | Metadata is not a substitute for first-class fields when a value is used for access, lifecycle, privacy, backup, restore, export, or reporting. --- ## 6. Table: `uckkarchive` Purpose: ```text Activity instance and root archive/media library configuration. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable archive activity UUID. | | `course` | int | Yes | Moodle course ID. | | `name` | char | Yes | Activity name. | | `intro` | text | No | Moodle intro field. | | `introformat` | int | Yes | Moodle intro format. | | `defaultvisibility` | char | Yes | Default visibility for new items/media. | | `defaultmediastatus` | char | Yes | Default media lifecycle state. | | `defaultvalidationstate` | char | Yes | Default validation state. | | `enablemedia` | int | Yes | Whether media library features are enabled. | | `enablecontentadvisories` | int | Yes | Whether content advisory features are enabled. | | `enableexternalworks` | int | Yes | Whether external work references are enabled. | | `enableexports` | int | Yes | Whether export features are enabled. | | `enablepublicview` | int | Yes | Whether public visibility is allowed. | | `enablerestrictedrecords` | int | Yes | Whether restricted records are allowed. | | `configjson` | text | No | JSON configuration for module-level behavior. | | `timecreated` | int | Yes | Creation time. | | `timemodified` | int | Yes | Modified time. | Rules: ```text The activity instance is the root context for archive, media, content advisory, and export records. The activity instance does not own grades or enrolments. ``` --- ## 7. Table: `uckkarchive_item` Purpose: ```text Archive memory item, pedagogical item, evidence item, institutional memory item, or item-level record that may reference media. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable archive item UUID. | | `archiveid` | int | Yes | Parent `uckkarchive`. | | `courseid` | int | Yes | Moodle course ID. | | `cmid` | int | Yes | Course module ID. | | `contextid` | int | Yes | Moodle context ID. | | `userid` | int | No | Primary associated user. | | `itemtype` | char | Yes | Archive item type. | | `title` | char | Yes | Item title. | | `summary` | text | No | Short summary. | | `content` | text | No | Rich content/editor content. | | `contentformat` | int | Yes | Format for `content`. | | `status` | char | Yes | Archive item status. | | `visibility` | char | Yes | Visibility value. | | `validationstate` | char | Yes | Validation state. | | `versionno` | int | Yes | Current version number. | | `currentrevisionid` | int | No | Current revision record. | | `provenanceid` | int | No | Current provenance record. | | `provenancehash` | char | No | Hash for provenance state. | | `retentionclass` | char | Yes | Retention classification. | | `redactionstate` | char | Yes | Redaction state. | | `createdby` | int | Yes | Creator. | | `modifiedby` | int | Yes | Last modifier. | | `validatedby` | int | No | Validator. | | `timevalidated` | int | No | Validation timestamp. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Canonical `itemtype` values: ```text proof decision_snapshot minutes challenge_result course_work portfolio_item kristal_source integrity_summary public_summary institutional_source media_context external_work_context content_advisory_context ``` Rules: ```text Archive items are not media objects. Archive items may reference media objects through relation records. Archive items may contain editor content and item files. Archive items preserve meaning, context, validation, and institutional/pedagogical memory. ``` --- ## 8. Table: `uckkarchive_proof` Purpose: ```text Proof/evidence record associated with an archive item, challenge, validation, portfolio, media, or restricted review. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable proof UUID. | | `archiveid` | int | Yes | Parent archive. | | `itemid` | int | No | Related archive item. | | `mediaid` | int | No | Related media object. | | `courseid` | int | Yes | Course ID. | | `cmid` | int | Yes | Course module ID. | | `contextid` | int | Yes | Context ID. | | `userid` | int | No | Submitter/owner. | | `prooftype` | char | Yes | Proof type. | | `title` | char | Yes | Proof title. | | `description` | text | No | Proof description. | | `status` | char | Yes | Lifecycle state. | | `visibility` | char | Yes | Visibility state. | | `validationstate` | char | Yes | Validation state. | | `sourcecomponent` | char | No | Originating component. | | `sourcearea` | char | No | Originating area. | | `sourceid` | int | No | Originating record ID. | | `retentionclass` | char | Yes | Retention classification. | | `redactionstate` | char | Yes | Redaction state. | | `createdby` | int | Yes | Creator. | | `modifiedby` | int | Yes | Last modifier. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Rules: ```text Proofs can link to archive items or media. Proof records do not own grades or challenge workflow. Restricted proofs require service-layer and file-layer checks. ``` --- ## 9. Table: `uckkarchive_kristal` Purpose: ```text Kristal record preserved as archive/media knowledge, symbolic structure, or pedagogical memory object. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable Kristal UUID. | | `archiveid` | int | Yes | Parent archive. | | `itemid` | int | No | Related archive item. | | `mediaid` | int | No | Related media. | | `title` | char | Yes | Kristal title. | | `summary` | text | No | Kristal summary. | | `kristaltype` | char | Yes | Kristal type. | | `status` | char | Yes | Lifecycle state. | | `visibility` | char | Yes | Visibility value. | | `validationstate` | char | Yes | Validation state. | | `provenanceid` | int | No | Provenance record. | | `versionno` | int | Yes | Version number. | | `createdby` | int | Yes | Creator. | | `modifiedby` | int | Yes | Last modifier. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Rules: ```text Kristals may reference media. Kristals are archive-owned records. Kristals do not own external authority domains. ``` --- ## 10. Table: `uckkarchive_prov` Purpose: ```text Provenance record explaining origin, source, method, actor, context, and trust lineage. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable provenance UUID. | | `archiveid` | int | Yes | Parent archive. | | `itemid` | int | No | Archive item. | | `mediaid` | int | No | Media object. | | `mediaversionid` | int | No | Media version. | | `externalworkid` | int | No | External work. | | `provenancetype` | char | Yes | Provenance value. | | `sourcecomponent` | char | No | Source component. | | `sourcearea` | char | No | Source area. | | `sourceid` | char | No | Source identifier. | | `sourcetitle` | char | No | Source title. | | `sourceurl` | text | No | Source URL/reference. | | `sourcehash` | char | No | Source hash. | | `actorid` | int | No | Actor. | | `statement` | text | No | Provenance statement. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Rules: ```text Provenance explains origin. Provenance does not grant authority. Provenance may contain personal or sensitive data and must be privacy-aware. ``` --- ## 11. Table: `uckkarchive_rev` Purpose: ```text Revision history for archive items, media metadata, validation changes, provenance changes, restriction changes, and content advisory changes. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable revision UUID. | | `archiveid` | int | Yes | Parent archive. | | `itemid` | int | No | Archive item. | | `mediaid` | int | No | Media object. | | `mediaversionid` | int | No | Media version. | | `contentmarkerid` | int | No | Content marker. | | `revisiontype` | char | Yes | Revision type. | | `versionno` | int | Yes | Version number. | | `reason` | text | Yes | Reason for change. | | `beforejson` | text | No | Safe previous-state JSON. | | `afterjson` | text | No | Safe new-state JSON. | | `createdby` | int | Yes | Actor. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | Rules: ```text No meaningful archive/media/advisory state change is silent. Sensitive previous values must not be stored unredacted in revision JSON. ``` --- ## 12. Table: `uckkarchive_export` Purpose: ```text Export request, export package, export manifest, and export status record. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable export UUID. | | `archiveid` | int | Yes | Parent archive. | | `userid` | int | Yes | Export requester. | | `exporttype` | char | Yes | Export type. | | `scope` | char | Yes | Export scope. | | `format` | char | Yes | Export format. | | `status` | char | Yes | Export status. | | `manifestjson` | text | No | Manifest JSON. | | `includeditems` | text | No | JSON list of item UUIDs. | | `includedmedia` | text | No | JSON list of media UUIDs. | | `includedexternalworks` | text | No | JSON list of external work UUIDs. | | `includedmarkers` | text | No | JSON list of content marker UUIDs. | | `redactionmode` | char | Yes | Redaction/export filtering mode. | | `expiresat` | int | No | Export expiry timestamp. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Rules: ```text Exports must use manifest.json. Exports must not bypass visibility, redaction, privacy, cultural protocol, or advisory policy. ``` --- ## 13. Table: `uckkarchive_media` Purpose: ```text First-class media object managed by the self-contained media library. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable media UUID. | | `archiveid` | int | Yes | Parent archive. | | `courseid` | int | Yes | Course ID. | | `cmid` | int | Yes | Course module ID. | | `contextid` | int | Yes | Context ID. | | `sourceid` | int | No | Media source record. | | `externalworkid` | int | No | External work reference. | | `title` | char | Yes | Media title. | | `description` | text | No | Media description. | | `mediatype` | char | Yes | Media type. | | `mimetype` | char | No | MIME type of primary/original file. | | `status` | char | Yes | Media lifecycle state. | | `visibility` | char | Yes | Visibility value. | | `audiencesuitability` | char | Yes | Audience suitability. | | `validationstate` | char | Yes | Validation state. | | `currentversionid` | int | No | Current media version. | | `originalversionid` | int | No | Original media version. | | `durationseconds` | int | No | Audio/video duration. | | `pagecount` | int | No | Document/page count. | | `language` | char | No | Language code. | | `license` | char | No | License/rights label. | | `rightsstatement` | text | No | Rights statement. | | `provenanceid` | int | No | Provenance record. | | `retentionclass` | char | Yes | Retention classification. | | `redactionstate` | char | Yes | Redaction state. | | `createdby` | int | Yes | Creator. | | `modifiedby` | int | Yes | Last modifier. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Canonical `mediatype` values: ```text image video audio document pdf text transcript caption thumbnail preview derivative archive_package external_reference other ``` Rules: ```text Media is a first-class domain object. Media is not merely a file attached to an archive item. Media may reference external works without copying external files. ``` --- ## 14. Table: `uckkarchive_media_version` Purpose: ```text Version record for media files, replacements, derivatives, previews, thumbnails, captions, transcripts, and metadata-significant media changes. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable media version UUID. | | `archiveid` | int | Yes | Parent archive. | | `mediaid` | int | Yes | Parent media object. | | `versionno` | int | Yes | Version number. | | `versiontype` | char | Yes | Version type. | | `filearea` | char | Yes | Moodle File API area. | | `filename` | char | No | Stored/display filename. | | `mimetype` | char | No | MIME type. | | `filesize` | int | No | File size. | | `contenthash` | char | No | Moodle/content hash. | | `sha256` | char | No | Portable hash. | | `durationseconds` | int | No | Duration. | | `pagecount` | int | No | Page count. | | `width` | int | No | Image/video width. | | `height` | int | No | Image/video height. | | `status` | char | Yes | Version status. | | `iscurrent` | int | Yes | Whether this is the current version. | | `createdby` | int | Yes | Creator. | | `reason` | text | No | Version reason. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | Canonical `versiontype` values: ```text original replacement preview thumbnail derivative caption transcript attachment metadata_revision ``` Rules: ```text Media files are not overwritten silently. Meaningful media changes create media version records. Generated derivatives are tracked separately from original files. ``` --- ## 15. Table: `uckkarchive_media_relation` Purpose: ```text Graph relation between media, archive items, Kristals, collections, external works, content markers, and other media. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable relation UUID. | | `archiveid` | int | Yes | Parent archive. | | `fromtype` | char | Yes | Source object type. | | `fromid` | int | Yes | Source object ID. | | `totype` | char | Yes | Target object type. | | `toid` | int | Yes | Target object ID. | | `relationtype` | char | Yes | Relation type. | | `sortorder` | int | Yes | Ordering. | | `createdby` | int | Yes | Creator. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | Canonical `relationtype` values: ```text belongs_to_item belongs_to_kristal belongs_to_collection is_derivative_of is_translation_of is_excerpt_of is_proof_for is_source_for replaces references duplicates references_external_work contains_content_marker ``` Rules: ```text Relations describe meaning. Relations do not copy files. Relations do not transfer external authority. ``` --- ## 16. Table: `uckkarchive_media_tag` Purpose: ```text General media tags for search, categorization, teaching use, and organization. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable tag UUID. | | `archiveid` | int | Yes | Parent archive. | | `mediaid` | int | Yes | Media object. | | `tagkey` | char | Yes | Machine tag key. | | `taglabel` | char | Yes | Display label. | | `tagtype` | char | Yes | Tag category. | | `createdby` | int | Yes | Creator. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | Rules: ```text Media tags support discovery. Content advisories use content advisory tables, not generic media tags. ``` --- ## 17. Table: `uckkarchive_media_collection` Purpose: ```text Reusable media set, bundle, course pack, evidence pack, public set, restricted bundle, or pedagogical media library collection. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable collection UUID. | | `archiveid` | int | Yes | Parent archive. | | `title` | char | Yes | Collection title. | | `description` | text | No | Collection description. | | `collectiontype` | char | Yes | Collection type. | | `status` | char | Yes | Lifecycle state. | | `visibility` | char | Yes | Visibility value. | | `audiencesuitability` | char | Yes | Suitability. | | `createdby` | int | Yes | Creator. | | `modifiedby` | int | Yes | Last modifier. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Canonical `collectiontype` values: ```text course_pack kristal_source_pack challenge_evidence_pack assembly_record_pack public_media_set restricted_proof_bundle content_advisory_set external_work_set ``` --- ## 18. Table: `uckkarchive_media_collection_item` Purpose: ```text Membership and ordering of media objects inside collections. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable membership UUID. | | `archiveid` | int | Yes | Parent archive. | | `collectionid` | int | Yes | Parent collection. | | `mediaid` | int | Yes | Media object. | | `sortorder` | int | Yes | Sort order. | | `role` | char | No | Role inside collection. | | `createdby` | int | Yes | Creator. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | Rules: ```text A media object may belong to multiple collections. Collections do not duplicate media files. ``` --- ## 19. Table: `uckkarchive_content_tag` Purpose: ```text Reusable content advisory, cultural sensitivity, cultural protocol, suitability, or restriction tag. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable content tag UUID. | | `archiveid` | int | No | Optional archive scope; null for global module tag. | | `tagkey` | char | Yes | Machine key. | | `taglabel` | char | Yes | Display label. | | `tagtype` | char | Yes | Tag type. | | `severity` | char | Yes | Severity. | | `description` | text | No | Description. | | `recommendedaction` | text | No | Teaching/access recommendation. | | `requirescontext` | int | Yes | Whether context is required. | | `requiresreview` | int | Yes | Whether human review is required. | | `createdby` | int | Yes | Creator. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Canonical content tag examples: ```text sexual_violence violence racism colonial_violence death self_harm substance_use nudity explicit_language culturally_sensitive sacred_content ceremonial_content restricted_knowledge grief_or_mourning requires_context not_for_children ``` Canonical `tagtype` values: ```text content_advisory cultural_protocol audience_suitability teaching_context access_restriction ``` Canonical `severity` values: ```text notice moderate strong restricted ``` --- ## 20. Table: `uckkarchive_content_tag_set` Purpose: ```text Reusable vocabulary or grouped tag set for advisory, cultural protocol, classroom suitability, integrity sensitivity, or youth access. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable tag set UUID. | | `archiveid` | int | No | Optional archive scope. | | `setkey` | char | Yes | Machine key. | | `setlabel` | char | Yes | Display label. | | `settype` | char | Yes | Set type. | | `description` | text | No | Description. | | `status` | char | Yes | Lifecycle state. | | `createdby` | int | Yes | Creator. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Canonical tag set examples: ```text general_advisories cultural_protocols classroom_suitability integrity_sensitive youth_access ``` Rules: ```text A tag set groups advisory tags into reusable vocabularies. Tag sets do not replace individual content tags or content markers. ``` --- ## 21. Table: `uckkarchive_content_marker` Purpose: ```text Location-specific advisory or cultural protocol marker attached to internal media, archive items, media versions, external works, or manual references. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable content marker UUID. | | `archiveid` | int | Yes | Parent archive. | | `tagid` | int | Yes | Content tag. | | `tagsetid` | int | No | Tag set. | | `mediaid` | int | No | Media object. | | `mediaversionid` | int | No | Media version. | | `itemid` | int | No | Archive item. | | `externalworkid` | int | No | External work. | | `locator_type` | char | Yes | Locator type. | | `locator_start` | char | No | Locator start. | | `locator_end` | char | No | Locator end. | | `locator_label` | char | No | Human-readable locator. | | `advisorytext` | text | No | Advisory note. | | `audiencesuitability` | char | Yes | Audience suitability. | | `reviewstate` | char | Yes | Review state. | | `visibility` | char | Yes | Marker visibility. | | `createdby` | int | Yes | Creator. | | `reviewedby` | int | No | Reviewer. | | `timereviewed` | int | No | Review timestamp. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Rules: ```text A content marker locates advisory meaning. A content marker may point to an external work without copying external content. A content marker does not ban media by itself. ``` --- ## 22. Table: `uckkarchive_content_review` Purpose: ```text Human review record for content markers, cultural protocol notes, suitability, advisory status, and restriction decisions. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable review UUID. | | `archiveid` | int | Yes | Parent archive. | | `markerid` | int | No | Content marker. | | `tagid` | int | No | Content tag. | | `mediaid` | int | No | Media object. | | `externalworkid` | int | No | External work. | | `reviewstate` | char | Yes | Review state. | | `decision` | char | Yes | Review decision. | | `reviewnote` | text | No | Review note. | | `recommendedaction` | text | No | Access/teaching recommendation. | | `reviewedby` | int | Yes | Reviewer. | | `visibility` | char | Yes | Visibility. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Canonical review states: ```text draft pending_review reviewed approved contested retired ``` Rules: ```text AI may suggest advisory tags or markers. Human review is required before advisory status becomes approved. Cultural protocol review cannot be replaced by AI. ``` --- ## 23. Table: `uckkarchive_external_work` Purpose: ```text Reference record for a work not produced by UCKK that may be taught, tagged, reviewed, cited, or linked to archive/media records. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable external work UUID. | | `archiveid` | int | No | Optional parent archive. | | `worktype` | char | Yes | External work type. | | `title` | char | Yes | Work title. | | `creator` | char | No | Author/director/creator. | | `publisher` | char | No | Publisher/studio/source. | | `publicationyear` | int | No | Year. | | `identifier` | char | No | ISBN/DOI/URL/catalog ID. | | `sourceurl` | text | No | URL/reference. | | `rightsstatement` | text | No | Rights/copyright statement. | | `sourceownership` | char | Yes | Ownership/source category. | | `audiencesuitability` | char | Yes | Suitability. | | `visibility` | char | Yes | Visibility. | | `createdby` | int | Yes | Creator. | | `modifiedby` | int | Yes | Last modifier. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Canonical `worktype` values: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` Rules: ```text External works may be referenced without being copied. The archive must not imply ownership over third-party works. Content markers can point to pages, timestamps, scenes, chapters, sections, or URL fragments of external works. ``` --- ## 24. Table: `uckkarchive_media_source` Purpose: ```text Source/rights/origin record describing whether a media object is UCKK-created, submitted, imported, licensed, external, public domain, or reference-only. ``` Required fields: | Field | Type | Required | Meaning | |---|---|---:|---| | `id` | int | Yes | Primary key. | | `uuid` | char(36) | Yes | Portable media source UUID. | | `archiveid` | int | Yes | Parent archive. | | `mediaid` | int | No | Media object. | | `externalworkid` | int | No | External work. | | `sourcetype` | char | Yes | Media source value. | | `sourceownership` | char | Yes | Ownership/source category. | | `license` | char | No | License value. | | `rightsstatement` | text | No | Rights statement. | | `attribution` | text | No | Attribution. | | `sourceurl` | text | No | Source URL/reference. | | `createdby` | int | Yes | Creator. | | `metadata` | text | No | JSON metadata. | | `timecreated` | int | Yes | Creation timestamp. | | `timemodified` | int | Yes | Modified timestamp. | Canonical `sourcetype` values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Canonical `sourceownership` values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Rules: ```text Media source records support rights, provenance, advisory, and export decisions. Source records do not transfer ownership from external rights holders. ``` --- ## 25. Status values Archive item statuses: ```text draft submitted under_review validated published restricted contested invalidated superseded archived ``` Media statuses: ```text draft submitted active restricted superseded archived deleted_soft ``` Export statuses: ```text queued processing ready failed expired purged ``` Content review states: ```text draft pending_review reviewed approved contested retired ``` --- ## 26. Visibility values Canonical visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Compatibility rule: ```text institutional must normalize to institution. ``` Rules: ```text Visibility does not replace capability checks. Restricted cultural visibility requires cultural protocol checks. Restricted integrity visibility requires restricted integrity checks. ``` --- ## 27. Validation states Canonical validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Rules: ```text Validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot approve cultural protocol access. AI cannot close contestations. ``` --- ## 28. Audience suitability values Canonical audience suitability values: ```text general guided mature restricted restricted_cultural restricted_integrity staff_only ``` Rules: ```text Audience suitability affects responsible access and teaching conditions. Suitability is not the same as visibility. Suitability can be refined by content markers. ``` --- ## 29. Retention classes Canonical retention classes: ```text draft_short course_operational portfolio_user proof_evidence institutional_memory restricted_integrity restricted_cultural export_generated external_snapshot ``` Rules: ```text Retention controls preservation/deletion behavior. Retention does not automatically grant visibility. ``` --- ## 30. Redaction states Canonical redaction states: ```text none partial full anonymised restricted deleted ``` Rules: ```text Redaction is persistent state. Redaction must apply to services, UI, export, privacy export, backup, and restore. ``` --- ## 31. File API mapping Component: ```text mod_uckkarchive ``` Archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File area registry: ```text classes/local/file_area_registry.php ``` Rules: ```text All file areas are centralized in file_area_registry. Pluginfile handling, services, privacy provider, backup, restore, and tests use the same registry. ``` --- ## 32. Index and uniqueness requirements Required unique keys: ```text uckkarchive.uuid uckkarchive_item.uuid uckkarchive_proof.uuid uckkarchive_kristal.uuid uckkarchive_prov.uuid uckkarchive_rev.uuid uckkarchive_export.uuid uckkarchive_media.uuid uckkarchive_media_version.uuid uckkarchive_media_relation.uuid uckkarchive_media_tag.uuid uckkarchive_media_collection.uuid uckkarchive_media_collection_item.uuid uckkarchive_content_tag.uuid uckkarchive_content_tag_set.uuid uckkarchive_content_marker.uuid uckkarchive_content_review.uuid uckkarchive_external_work.uuid uckkarchive_media_source.uuid ``` Recommended functional indexes: ```text archiveid courseid cmid contextid userid status visibility validationstate mediaid itemid externalworkid tagid tagsetid collectionid timecreated timemodified ``` Recommended composite indexes: ```text archiveid,status archiveid,visibility archiveid,validationstate archiveid,mediaid archiveid,itemid archiveid,externalworkid archiveid,tagid archiveid,collectionid mediaid,versionno mediaid,iscurrent collectionid,sortorder tagid,reviewstate externalworkid,locator_type ``` --- ## 33. Metadata JSON rules JSON metadata may store: ```text display hints non-authority UI preferences import details external IDs non-critical source notes search hints format-specific media details AI suggestion details teaching context notes ``` JSON metadata must not be the only storage location for: ```text capability decisions visibility status validation state media lifecycle state content advisory review state cultural restriction state file area UUID primary relations privacy deletion state retention class redaction state export authority ``` --- ## 34. Privacy data model rules Tables that may contain personal data: ```text uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Privacy provider must cover: ```text user-linked records creator/modifier/reviewer fields uploaded files media files content review notes restricted records cultural protocol notes export packages manifest files ``` Rules: ```text Privacy export must not expose third-party restricted data. Cultural protocol notes may require redaction even when the user owns related content. External work references must not imply ownership or authorization. ``` --- ## 35. Backup and restore data model rules Backup must include: ```text archive instance archive items proofs Kristals provenance revisions exports media media versions media relations media tags media collections media collection membership content tags content tag sets content markers content reviews external works media source records all active file areas ``` Restore must preserve: ```text UUIDs relations collection membership content marker locators external work references media source records visibility validation state retention class redaction state restricted cultural state restricted integrity state export manifest metadata ``` Restore must not create authority in external systems. --- ## 36. Export manifest data model Canonical manifest file: ```text manifest.json ``` Manifest includes: ```text plugin component archive id archive uuid export id export uuid export timestamp export actor export reason archive item uuids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Rules: ```text Exports are portable and explainable. Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` --- ## 37. Data model final rule ```text mod_uckkarchive owns a self-contained archive, media library, and content advisory data model. Archive records preserve meaning. Media records manage reusable media objects. Media versions preserve file history. Collections organize media. Relations describe graph meaning. Content advisories describe responsible access, cultural protocol, and suitability. External works allow foreign media to be referenced without claiming ownership. Provenance explains origin. Revisions preserve change. Exports preserve portable memory. All files remain in Moodle File API. All authority checks remain server-side. All final implementation must conform to this data model. ``` ================================================================================================ FILE: mod/uckkarchive/docs/05_media_library.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: f38c6ed92adfed0e7868e1960db43c23597de0fdf6ec321cfe2bb5052b7bc285 CONTENT_BYTES: 24331 ================================================================================================ # 05 — Media Library **Path:** `docs/05_media_library.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Self-contained media library subsystem inside the UCKK Archive Moodle activity module. --- ## 1. Purpose This document defines the final media-library architecture for `mod_uckkarchive`. The media library is a first-class subsystem of the module. It is not a public folder. It is not only a set of file attachments. It is not a generic archive item subtype. It is a managed media domain with its own records, versions, relations, collections, tags, source metadata, content advisories, cultural protocol markers, export identity, and Moodle File API storage. Canonical formula: ```text mod_uckkarchive = archive engine + media library engine + content advisory system + Moodle adapter layer ``` --- ## 2. Core decision Media is a first-class object. Canonical media object: ```text uckkarchive_media ``` Canonical media version object: ```text uckkarchive_media_version ``` Canonical media collection object: ```text uckkarchive_media_collection ``` Canonical media relation object: ```text uckkarchive_media_relation ``` Canonical media tag object: ```text uckkarchive_media_tag ``` The module stores actual media files through Moodle File API. The module stores media identity, metadata, versioning, collections, relations, tags, content markers, provenance, visibility, suitability, and source information in module-owned tables. --- ## 3. Media library responsibilities The media library owns: ```text media records media versions media file identity media metadata media lifecycle state media visibility media source information media ownership metadata media collections media collection membership media relations media tags media content advisories media cultural protocol markers media review state media export identity media restore identity media privacy surface ``` The media library does not own: ```text grades transcripts course enrolments Assembly decision authority integrity case authority institutional report authority external copyright ownership third-party work ownership ``` The media library may reference external works without claiming ownership over those works. --- ## 4. Moodle integration boundary The media library uses Moodle for: ```text course module context users roles groups capabilities File API Privacy API Backup API Restore API External Services API events settings language strings rendering scheduled tasks ``` The media library must not bypass Moodle’s context, capability, file, privacy, backup, restore, service, or event systems. --- ## 5. Required media tables The media library requires these tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item uckkarchive_media_source ``` The content advisory subsystem extends media management with: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work ``` These tables are part of the current target architecture. They are not optional. --- ## 6. `uckkarchive_media` `uckkarchive_media` is the canonical table for media objects. A media object represents the managed intellectual/media entity. It is not the same as a single file. A media object may have: ```text one original file many versions many derivatives many thumbnails many captions many transcripts many attachments many relations many content markers many collection memberships ``` Recommended fields: ```text id uuid archiveid courseid cmid contextid ownerid createdby modifiedby sourceid title subtitle description mediatype mimetype status visibility audiencesuitability licensekey rightsstatement language duration pagecount hashoriginal currentversionid provenanceid metadata timecreated timemodified ``` Canonical `mediatype` values: ```text image video audio document pdf transcript caption thumbnail preview derivative source_package external_reference other ``` --- ## 7. `uckkarchive_media_version` `uckkarchive_media_version` stores version history for media objects. A media version represents a meaningful media state. Media must not be silently overwritten. A new version is created when: ```text the original file is replaced a corrected file is uploaded metadata affecting meaning is changed a transcript is corrected captions are corrected a derivative is generated or replaced rights/license metadata changes visibility changes in a way that affects access content advisories are materially changed cultural protocol state changes ``` Recommended fields: ```text id uuid mediaid versionno versionlabel filearea fileitemid filename mimetype filesize contenthash status createdby reason changesummary metadata timecreated ``` Media versioning permission: ```text mod/uckkarchive:versionmedia ``` --- ## 8. `uckkarchive_media_collection` `uckkarchive_media_collection` stores reusable groups of media. A collection is not a folder in the filesystem. A collection is an ordered or structured media grouping. Examples: ```text course pack Kristal source pack challenge evidence pack assembly record pack public media set restricted proof bundle cultural protocol set external work study set ``` Recommended fields: ```text id uuid archiveid courseid contextid ownerid title description collectiontype visibility audiencesuitability createdby modifiedby metadata timecreated timemodified ``` Canonical `collectiontype` values: ```text course_pack kristal_pack challenge_pack assembly_pack proof_bundle public_set restricted_set cultural_protocol_set external_work_set custom ``` --- ## 9. `uckkarchive_media_collection_item` `uckkarchive_media_collection_item` stores membership of media objects in collections. Recommended fields: ```text id collectionid mediaid sortorder role addedby metadata timecreated ``` Canonical membership roles: ```text primary supporting source derivative preview required optional restricted contextual ``` A media object may belong to multiple collections. A collection does not own the media object. --- ## 10. `uckkarchive_media_relation` `uckkarchive_media_relation` stores graph relationships between media objects, archive items, Kristals, collections, external works, and proof records. Canonical relation types: ```text belongs_to_item belongs_to_kristal belongs_to_collection is_derivative_of is_translation_of is_excerpt_of is_proof_for is_source_for replaces references duplicates references_external_work contains_content_marker ``` Recommended fields: ```text id uuid sourcetype sourceid targettype targetid relationtype direction createdby metadata timecreated ``` Relation rules: ```text Relations describe meaning. Relations do not transfer ownership. Relations do not grant access automatically. Relations must be filtered by policy before display or export. ``` --- ## 11. `uckkarchive_media_tag` `uckkarchive_media_tag` stores media classification tags. Media tags are general descriptive tags. Content advisory tags are stored separately in `uckkarchive_content_tag`. Recommended fields: ```text id mediaid tagkey tagtype createdby metadata timecreated ``` Canonical `tagtype` values: ```text topic discipline format language pedagogical technical source rights custom ``` Tag rule: ```text Media tags describe media. Content advisory tags describe suitability, sensitivity, or protocol conditions. ``` --- ## 12. `uckkarchive_media_source` `uckkarchive_media_source` records source and ownership classification for media. Canonical media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Canonical source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Recommended fields: ```text id uuid mediaid externalworkid sourcekind ownershipkind sourcecomponent sourceurl sourcetitle sourceauthor licensekey rightsstatement citation createdby metadata timecreated timemodified ``` Source rule: ```text The module may preserve source metadata. The module must not imply ownership over third-party media. The module may reference foreign media without copying it. ``` --- ## 13. External works External works are represented by: ```text uckkarchive_external_work ``` External works are media or cultural objects not produced by UCKK. Examples: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` Recommended fields: ```text id uuid worktype title subtitle creator publisher publicationyear identifier url citation language country rightsstatement licensekey metadata timecreated timemodified ``` External work rules: ```text An external work can be referenced without copying the work. A content marker can point to a precise location in an external work. The module can store teaching notes, advisories, cultural protocols, citations, and locators for external works. The module must not claim ownership over external works. ``` --- ## 14. Content advisories The media library includes content advisories as a first-class subsystem. Canonical content advisory tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review ``` A content advisory does not ban media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. User-facing terms may include: ```text content advisory content warning trigger warning cultural advisory cultural protocol audience suitability ``` System-level terminology should prefer: ```text content advisory content marker content tag content review cultural protocol ``` Avoid using `trigger` alone as a database/system name because it can be confused with database triggers. --- ## 15. Content advisory tags `uckkarchive_content_tag` defines reusable advisory and cultural protocol tags. Examples: ```text sexual_violence violence racism colonial_violence death self_harm substance_use nudity explicit_language culturally_sensitive sacred_content ceremonial_content restricted_knowledge grief_or_mourning requires_context not_for_children ``` Cultural protocol examples: ```text community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context restricted_knowledge sacred_content ceremonial_content ``` Recommended fields: ```text id uuid tagkey label description category severitydefault iscultural isrestricted requiresreview createdby metadata timecreated timemodified ``` Canonical advisory severity values: ```text notice moderate strong restricted ``` --- ## 16. Content tag sets `uckkarchive_content_tag_set` groups advisory tags into reusable vocabularies. Examples: ```text general_advisories cultural_protocols classroom_suitability integrity_sensitive youth_access ``` Recommended fields: ```text id uuid setkey name description visibility createdby metadata timecreated timemodified ``` Content tag set rule: ```text Tag sets define advisory vocabularies. Tag sets do not assign advisories to media by themselves. Assignments happen through content markers. ``` --- ## 17. Content markers `uckkarchive_content_marker` links a content advisory tag to a precise location in media, archive material, or external work. Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Examples: ```text Movie Maïna -> sexual_violence -> 01:12:30-01:15:10 Book The Body Keeps the Score -> sexual_violence -> page 42-45 PDF -> culturally_sensitive -> page 7 Audio -> grief_or_mourning -> 00:08:12-00:09:40 Website -> colonial_violence -> url_fragment #section-3 ``` Recommended fields: ```text id uuid tagid targettype targetid externalworkid mediaid mediaversionid archiveitemid locatortype locatorstart locatorend locatorlabel audiencesuitability severity reviewstate visibility createdby metadata timecreated timemodified ``` Content marker rule: ```text A content marker can point to internal media, media versions, archive items, external works, or manual references. A marker must include enough locator information to be useful without storing unauthorized copies of external content. ``` --- ## 18. Content reviews `uckkarchive_content_review` records human review of advisory markers, cultural protocol notes, suitability, and restriction decisions. Canonical review states: ```text draft pending_review reviewed approved contested retired ``` Recommended fields: ```text id uuid markerid reviewstate reviewedby reviewnote decision audiencesuitability visibility requirescontext requirespermission createdby metadata timecreated timemodified ``` Content review rule: ```text AI may suggest tags or markers. Human review is required before advisory state becomes approved. Cultural protocol access cannot be approved by AI. ``` --- ## 19. Audience suitability Canonical audience suitability values: ```text general guided mature restricted restricted_cultural restricted_integrity staff_only ``` Suitability rule: ```text Audience suitability informs responsible access. It does not automatically hide media unless policy maps it to access restrictions. ``` Policy may use suitability to: ```text show advisory banners require confirmation require context notes restrict export restrict public display require elevated capability hide media from unsuitable audiences ``` --- ## 20. Media lifecycle Canonical media states: ```text draft submitted active restricted superseded archived deleted_soft ``` Lifecycle meaning: | State | Meaning | |---|---| | `draft` | Media exists but is not ready for general use. | | `submitted` | Media has been submitted for review or inclusion. | | `active` | Media is usable according to visibility and policy. | | `restricted` | Media is usable only under restricted access rules. | | `superseded` | Media has been replaced by a newer media object or version. | | `archived` | Media is preserved but not active for ordinary use. | | `deleted_soft` | Media is hidden/retained only for audit, recovery, or retention policy. | Lifecycle rule: ```text File existence is not media availability. Media status controls usability. Visibility controls access. Policy controls download and export. Retention controls deletion. Content advisories describe suitability, cultural protocol, and access conditions. ``` --- ## 21. Media visibility Canonical visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Visibility rule: ```text Visibility defines audience scope. Capabilities and policy still decide actual access. Restricted cultural material requires cultural protocol checks. Restricted integrity material requires integrity-specific checks. ``` --- ## 22. Media file areas Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Canonical content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File-area meanings: | File area | Purpose | |---|---| | `media_original` | Original uploaded or preserved media file. | | `media_preview` | Preview file for display. | | `media_thumbnail` | Generated or uploaded thumbnail. | | `media_derivative` | Generated derivative such as compressed video, converted image, or alternate format. | | `media_caption` | Caption file such as VTT/SRT. | | `media_transcript` | Transcript file. | | `media_attachment` | Supporting attachment. | | `content_review_files` | Files used during content advisory or cultural review. | | `external_work_reference_files` | Reference files or permitted metadata files for external works. | | `cultural_protocol_files` | Cultural protocol notes or permission files. | File-area rule: ```text All file areas are declared centrally in classes/local/file_area_registry.php. ``` --- ## 23. Media policy Media access policy belongs in: ```text classes/local/media_policy.php ``` Content advisory policy belongs in: ```text classes/local/content_policy.php ``` Policy methods include: ```text can_view_media can_download_original can_view_derivative can_view_thumbnail can_view_transcript can_edit_metadata can_add_version can_export_media can_view_restricted_media can_view_culturally_restricted can_manage_content_markers can_review_content_marker can_reference_external_work ``` Policy rule: ```text Controllers, templates, AMD modules, and output classes must not make final access decisions. ``` --- ## 24. Media services Required media services: ```text classes/external/get_media.php classes/external/get_media_item.php classes/external/get_media_card.php classes/external/search_media.php classes/external/add_media.php classes/external/update_media.php classes/external/delete_media.php classes/external/add_media_version.php classes/external/get_media_versions.php classes/external/get_media_relations.php classes/external/add_media_relation.php classes/external/remove_media_relation.php classes/external/get_media_collections.php classes/external/get_media_collection.php classes/external/add_media_collection.php classes/external/update_media_collection.php classes/external/add_media_to_collection.php classes/external/remove_media_from_collection.php classes/external/tag_media.php classes/external/untag_media.php ``` Required content advisory and external work services: ```text classes/external/get_content_tags.php classes/external/get_content_tag_sets.php classes/external/get_content_markers.php classes/external/add_content_marker.php classes/external/update_content_marker.php classes/external/delete_content_marker.php classes/external/review_content_marker.php classes/external/get_external_works.php classes/external/get_external_work.php classes/external/add_external_work.php classes/external/update_external_work.php ``` Service rule: ```text External services check context, capability, visibility, media lifecycle, content advisory policy, cultural protocol rules, restricted state, retention, and redaction. ``` --- ## 25. Media UI Required media UI controllers: ```text media.php ``` Required media templates: ```text templates/media_card.mustache templates/media_collection.mustache templates/media_library.mustache templates/media_relation_list.mustache templates/media_upload.mustache templates/media_version_list.mustache templates/content_advisory_panel.mustache templates/external_work_card.mustache ``` Required media AMD files: ```text amd/src/media.js amd/src/media_collection.js amd/src/content_advisory.js amd/src/external_work.js ``` UI rule: ```text The UI displays policy-filtered data. The UI may show advisory banners, locator markers, context notes, and restricted-state labels. The UI must not expose restricted metadata or hidden cultural protocol notes to unauthorized users. ``` --- ## 26. Media events Required media events: ```text classes/event/media_created.php classes/event/media_updated.php classes/event/media_version_created.php classes/event/media_collection_created.php classes/event/media_exported.php classes/event/content_marker_created.php classes/event/content_marker_reviewed.php classes/event/external_work_created.php ``` Event rule: ```text Events audit state changes. Events must not expose raw media content, restricted notes, hidden cultural protocol notes, or redacted data. ``` --- ## 27. Media tasks Required scheduled tasks: ```text classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php ``` Task responsibilities: ```text generate previews generate thumbnails generate derivatives maintain media search data maintain content marker index avoid bypassing policy ``` --- ## 28. Media export Media exports are generated by the archive export subsystem. Media export includes: ```text media metadata media UUIDs media versions file hashes file sizes mime types relations collections tags content markers content reviews external work references audience suitability cultural protocol flags visibility redaction state provenance manifest.json ``` Media export rule: ```text Export does not bypass permissions. Export does not bypass content advisory policy. Export does not bypass cultural protocol restrictions. Export does not imply ownership over external works. ``` --- ## 29. Media backup and restore Backup must preserve: ```text media records media versions media collections media collection membership media relations media tags media source records content tags content tag sets content markers content reviews external works media files content review files external work reference files cultural protocol files ``` Restore must preserve: ```text UUIDs relations collections markers review states visibility audience suitability restricted state provenance file hashes file areas ``` Restore rule: ```text Restore reconstructs module-owned media library state. Restore does not create external ownership authority. Restore does not make restricted media public. ``` --- ## 30. Media privacy Privacy provider must cover: ```text media created by user media modified by user media uploaded by user media versions created by user media collections created by user media relations created by user media tags created by user content markers created by user content reviews performed by user external works created by user media source records created by user files uploaded by user review notes containing personal data metadata containing personal data ``` Privacy rule: ```text Privacy export is not a permission bypass. Restricted third-party data must be redacted or filtered. Cultural protocol notes must not be exposed to unauthorized users. ``` --- ## 31. Media search Media search should support: ```text title description mediatype mimetype status visibility collection tag content advisory tag audience suitability source kind external work language rights/license provenance creator date ``` Search rule: ```text Search results must be permission-filtered. Restricted media must not appear to unauthorized users. Restricted content advisory details must not leak through search snippets. ``` --- ## 32. Required tests Required test areas: ```text media creation media update media deletion soft state media version creation media collection creation media collection membership media relation graph media tags media source records external works content advisory tags content tag sets content markers content reviews media file areas restricted media access culturally restricted access media export media backup media restore media privacy media search filtering ``` Required test files: ```text tests/media_library_test.php tests/content_advisory_test.php tests/external_work_test.php tests/file_api_test.php tests/privacy_provider_test.php tests/backup_restore_test.php tests/export_test.php tests/services_test.php tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` --- ## 33. Final rule The media library is self-contained inside `mod_uckkarchive`. It owns media objects, media versions, collections, relations, tags, source records, external work references, content advisories, cultural protocol markers, review states, and export identity. It uses Moodle File API for storage and Moodle APIs for lifecycle, access, privacy, backup, restore, events, services, and rendering. This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/06_file_api_and_storage.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 159d24abf8eafd621f45c44d303e2766cfc735e8a1804e83488916367bab9be9 CONTENT_BYTES: 25045 ================================================================================================ # 06 — File API and Storage **Path:** `docs/06_file_api_and_storage.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Moodle File API, file-area registry, archive files, media-library files, content advisory files, external work references, privacy, backup/restore, export, and pluginfile access rules. --- ## 1. Purpose This document defines the final file storage architecture for `mod_uckkarchive`. `mod_uckkarchive` is a Moodle-native activity module with a self-contained archive, media library, and content advisory system. All production files owned by the module are stored through Moodle File API. The module must not store production archive or media files in unmanaged public folders. The module must not store binary media files directly in custom database fields. The module must not use direct public file URLs as authority. --- ## 2. Core storage decision Canonical storage formula: ```text Moodle File API stores files. mod_uckkarchive tables store identity, metadata, state, policy, relations, and provenance. ``` The plugin owns: ```text archive file areas media file areas content advisory file areas export package file areas manifest file areas provenance file areas review file areas ``` Moodle owns the physical file storage mechanism. `mod_uckkarchive` owns the meaning, policy, visibility, lifecycle, metadata, and access logic around those files. --- ## 3. Moodle component Canonical File API component: ```text mod_uckkarchive ``` Every module-owned file must use: ```text component = mod_uckkarchive ``` No module-owned file may use another component as its storage authority. External plugins may reference archive/media records through APIs, but the file remains owned by `mod_uckkarchive`. --- ## 4. Central file-area registry The canonical file-area list is defined in: ```text classes/local/file_area_registry.php ``` This registry is the single source of truth for file areas. All of the following must use the registry: ```text lib.php pluginfile handler controllers external services forms privacy provider backup task backup steps restore task restore steps tests export package builder media file service content advisory service ``` No controller, service, form, task, or template may invent a file-area name directly. --- ## 5. Canonical archive file areas Archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` ### Archive file-area meaning | File area | Purpose | |---|---| | `intro` | Standard Moodle activity intro files. | | `item_content` | Embedded files used inside archive item rich content. | | `item_publicsummary` | Files attached to public or shareable summary content. | | `item_files` | General archive item attachments. | | `proof_files` | Evidence/proof attachments. | | `decision_attachments` | Preserved Assembly decision attachments owned as archive copies or references. | | `minutes_files` | Preserved minutes or institutional memory files. | | `kristal_files` | Kristal-related attached files. | | `portfolio_files` | Portfolio-linked archive files. | | `integrity_exports` | Restricted integrity-related archive export files. | | `provenance_files` | Source/provenance packages, references, or evidence files. | | `validation_files` | Files used during validation or review. | | `revision_files` | Files attached to revision history. | | `export_package` | Generated archive/media export package. | | `export_manifest` | Generated export manifest, usually `manifest.json`. | --- ## 6. Canonical media file areas Media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` ### Media file-area meaning | File area | Purpose | |---|---| | `media_original` | Original uploaded or imported media file. | | `media_preview` | Preview file optimized for display or teaching. | | `media_thumbnail` | Thumbnail or poster image. | | `media_derivative` | Generated or curated derivative file. | | `media_caption` | Caption/subtitle files. | | `media_transcript` | Transcript files. | | `media_attachment` | Supporting files attached to a media object. | Media file areas are linked to `uckkarchive_media` or `uckkarchive_media_version` records. The original file must not be overwritten silently. Media replacement creates a media version. --- ## 7. Canonical content advisory file areas Content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` ### Content advisory file-area meaning | File area | Purpose | |---|---| | `content_review_files` | Files attached to advisory review decisions. | | `external_work_reference_files` | Reference files or metadata packages for external works, when storage is permitted. | | `cultural_protocol_files` | Files documenting cultural protocol, access conditions, or review notes. | These areas support content advisories, cultural sensitivity tags, content markers, content reviews, external works, and audience suitability rules. They do not automatically make restricted cultural or sensitive content visible. --- ## 8. File-area grouping The registry must classify file areas into groups: ```text activity_intro archive_item proof kristal portfolio integrity provenance validation revision media content_advisory external_work export ``` The group determines: ```text allowed parent table expected itemid meaning privacy export behavior backup/restore mapping pluginfile policy download policy redaction behavior retention behavior ``` --- ## 9. Item ID rules Every File API area must have a predictable `itemid`. | File area group | Item ID points to | |---|---| | `activity_intro` | Moodle module context or activity instance, using Moodle conventions. | | `archive_item` | `uckkarchive_item.id` | | `proof` | `uckkarchive_proof.id` | | `kristal` | `uckkarchive_kristal.id` | | `portfolio` | `uckkarchive_item.id` or portfolio-specific archive item record. | | `integrity` | `uckkarchive_export.id`, `uckkarchive_item.id`, or integrity-restricted archive-owned record. | | `provenance` | `uckkarchive_prov.id` | | `validation` | `uckkarchive_rev.id` or validation/review record. | | `revision` | `uckkarchive_rev.id` | | `media` | `uckkarchive_media.id` or `uckkarchive_media_version.id`, depending on area. | | `content_advisory` | `uckkarchive_content_review.id` or `uckkarchive_content_marker.id`. | | `external_work` | `uckkarchive_external_work.id` | | `export` | `uckkarchive_export.id` | Item ID rules must be enforced by `classes/local/file_area_registry.php`. --- ## 10. Media item ID rules Media file areas use these target records: | File area | Item ID | |---|---| | `media_original` | `uckkarchive_media_version.id` | | `media_preview` | `uckkarchive_media_version.id` | | `media_thumbnail` | `uckkarchive_media.id` | | `media_derivative` | `uckkarchive_media_version.id` | | `media_caption` | `uckkarchive_media_version.id` | | `media_transcript` | `uckkarchive_media_version.id` | | `media_attachment` | `uckkarchive_media.id` | Rationale: ```text originals, derivatives, captions, transcripts, and previews are version-specific thumbnails and attachments may belong to the media object as a whole ``` A media version can have one original and multiple derivative/supporting files. --- ## 11. Content advisory item ID rules Content advisory file areas use these target records: | File area | Item ID | |---|---| | `content_review_files` | `uckkarchive_content_review.id` | | `external_work_reference_files` | `uckkarchive_external_work.id` | | `cultural_protocol_files` | `uckkarchive_content_review.id` or approved protocol record | Content advisory files may contain sensitive context. Access is controlled by content policy, cultural protocol policy, visibility, and capability. --- ## 12. External work storage decision External or foreign media is not automatically copied into UCKK storage. External works may be represented by: ```text metadata citation external identifier publisher/source information URL locator content advisory tags content markers cultural protocol notes teaching notes review notes ``` The archive may store a file for an external work only when storage is permitted by rights, license, policy, or institutional decision. When external content is not stored, the module may still store: ```text work metadata content markers page references timecode references scene references chapter references advisory tags review state audience suitability cultural protocol restrictions ``` External work records must not imply UCKK ownership of third-party media. --- ## 13. Content marker locator storage Content markers may identify sensitive or culturally restricted content inside internal or external works. Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Examples: ```text film -> content marker -> 01:12:30-01:15:10 book -> content marker -> page 42-45 PDF -> content marker -> page 7 audio -> content marker -> 00:08:12-00:09:40 website -> content marker -> url_fragment #section-3 ``` Locator metadata belongs in `uckkarchive_content_marker`. Files supporting the review belong in `content_review_files` or `cultural_protocol_files`. --- ## 14. Draft file workflow User uploads must use Moodle draft areas before being committed to permanent File API areas. Workflow: ```text upload to draft area validate draft file create or load target record save file to canonical file area store metadata and provenance create revision/version record where required trigger event return filtered response ``` Draft files must not be treated as permanent records. Draft files must not be exported. Draft files must not be used as proof until committed to a canonical file area. --- ## 15. Media upload workflow Media upload workflow: ```text create uckkarchive_media record create uckkarchive_media_version record move original file from draft area to media_original generate or queue thumbnail generate or queue preview extract or attach metadata store provenance apply initial visibility and suitability apply content advisory defaults trigger media_created ``` The module may queue derivative work using scheduled tasks. Generated files must be stored in canonical media file areas. Generated files must not overwrite originals. --- ## 16. Media version workflow Media version workflow: ```text load media object check mod/uckkarchive:versionmedia check media policy create new uckkarchive_media_version move uploaded file to media_original queue derivative generation record provenance record relation to previous version mark previous version as superseded where appropriate trigger media_version_created ``` A new media version is required when: ```text original file changes caption file changes materially transcript changes materially preview/derivative changes materially rights/license metadata changes materially content advisory state changes materially cultural protocol state changes materially ``` Minor display-only metadata changes may update the media record without creating a new file version, but must still be auditable when policy requires it. --- ## 17. Derivatives and generated files Generated files include: ```text preview files thumbnails transcoded derivatives captions derived from transcripts text extraction outputs search index support files ``` Generated files must be reproducible or explicitly marked as curated. Generated files must store: ```text source media uuid source version uuid generator generation time hash mime type size derivative type ``` Generated files must respect restrictions on the source media. A restricted source cannot produce unrestricted derivatives. --- ## 18. Pluginfile handler File serving is implemented through `lib.php` using the Moodle pluginfile callback. The pluginfile handler must: ```text require valid context resolve archive instance validate component validate file area through file_area_registry validate itemid load parent record check visibility check capability check media status check archive item status check content advisory policy check cultural protocol policy check restricted access policy check retention/redaction policy serve file only after all checks pass ``` The pluginfile handler must not: ```text serve unknown file areas serve files by direct URL alone serve restricted files to ordinary users serve deleted_soft media serve redacted files without policy approval serve external work references as if UCKK owned the content ``` --- ## 19. Download authority A file exists physically when Moodle File API stores it. A file is downloadable only when policy permits it. Download authority depends on: ```text context capability ownership visibility media status archive item status validation state restricted state content advisory state cultural protocol restrictions audience suitability retention state redaction state export policy ``` Direct file URL access is never sufficient authority. --- ## 20. Original media access Original media files are higher-risk than previews or thumbnails. Original media download requires: ```text mod/uckkarchive:downloadmedia context access media access media status access version access content advisory policy cultural protocol policy retention/redaction policy ``` Viewing a preview does not automatically grant access to the original. Exporting a preview does not automatically grant access to the original. --- ## 21. Restricted media Restricted media includes: ```text restricted restricted_integrity restricted_cultural staff_only redacted deleted_soft archived with limited access ``` Restricted media must not be served through ordinary media browsing. Restricted media must not appear in public search results. Restricted media must not be exported unless export policy permits it. Restricted cultural media requires cultural protocol checks. Restricted integrity media requires integrity-specific checks. --- ## 22. Content advisory access effects A content advisory does not automatically ban a file. A content advisory can require: ```text notice before viewing guided access mature audience access staff review cultural protocol check restricted access contextual teaching note exclusion from public export exclusion from youth-facing views ``` Content advisory policy belongs in: ```text classes/local/content_policy.php ``` Content advisory policy is consulted by: ```text media browsing media download archive item view export package generation search results course integration views public summary rendering ``` --- ## 23. Cultural protocol files Cultural protocol files may describe: ```text community permission rules elder review notes seasonal/contextual restrictions sacred or ceremonial content rules restricted knowledge rules public export prohibitions teaching context requirements ``` These files are sensitive by default. They require: ```text mod/uckkarchive:viewculturallyrestricted ``` or stricter policy rules. Cultural protocol notes must not be exposed in public output unless explicitly approved. --- ## 24. Privacy API storage obligations The privacy provider must declare and handle all module-owned file areas. Privacy provider path: ```text classes/privacy/provider.php ``` The provider must cover: ```text archive files media files media version files content advisory files external work reference files cultural protocol files export packages export manifests provenance files validation files revision files ``` Privacy export must not expose third-party restricted data, cultural protocol notes, or redacted material unless policy allows it. Deletion and anonymisation must preserve institutional memory where policy requires preservation. --- ## 25. Backup storage obligations Backup must include archive, media, content advisory, and external work file areas. Backup files: ```text backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php ``` Backup must include: ```text archive item files proof files media originals media versions media thumbnails media previews media derivatives media captions media transcripts media attachments content review files external work reference files cultural protocol files export packages export manifests provenance files validation files revision files ``` Backup must preserve file-area names exactly as defined by `file_area_registry`. --- ## 26. Restore storage obligations Restore must recreate file ownership only after records and mappings exist. Restore files: ```text backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` Restore must remap: ```text archive item ids proof ids Kristal ids provenance ids revision ids export ids media ids media version ids media relation ids media collection ids content tag ids content marker ids content review ids external work ids ``` Restore must not: ```text make restricted files public drop cultural protocol restrictions drop content advisory metadata drop redaction state regenerate exports as new authoritative packages create gradebook records create integrity case authority create Assembly decision authority ``` --- ## 27. Export package storage Export package files use: ```text export_package export_manifest ``` Canonical manifest filename: ```text manifest.json ``` Export packages may include: ```text archive records media records media versions selected files content markers content tags content reviews external work metadata relations collections provenance redaction information validation state ``` Export packages must not include restricted files unless export policy permits them. Export package generation must use: ```text classes/local/export_package.php classes/local/manifest_builder.php ``` --- ## 28. Manifest file hashes Every exported file entry must include: ```text file area itemid filename filepath contenthash sha256 or stronger hash where available mime type file size source uuid source version uuid where applicable redaction state restriction state ``` The manifest must allow an exported package to be audited without direct database access. --- ## 29. Search indexing files Search indexes or derived search metadata must not be stored as uncontrolled public files. Media search behavior belongs in: ```text classes/local/media_search.php ``` Content marker indexing belongs in scheduled task support: ```text classes/task/rebuild_content_marker_index.php ``` Search indexes must respect: ```text visibility content advisory policy cultural protocol restrictions restricted integrity policy redaction state deleted_soft state ``` --- ## 30. Scheduled file tasks Scheduled tasks that may create, update, or remove files: ```text classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/purge_expired_exports.php classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php ``` Task rules: ```text tasks reuse policy classes tasks do not bypass restrictions tasks preserve source file integrity tasks do not overwrite originals tasks log generated outputs tasks remove expired generated files according to retention policy ``` --- ## 31. Retention and deletion Deletion states: ```text active archived deleted_soft purged ``` Soft-deleted media must not be downloadable. Soft-deleted media may remain in Moodle File API until retention policy permits purge. Purging must remove: ```text files derivatives thumbnails captions transcripts attachments generated export copies orphaned draft-derived files ``` Purging must not remove evidence required for institutional, legal, cultural protocol, or integrity retention. --- ## 32. Redaction Redaction may apply to: ```text archive item files media previews media transcripts captions content advisory notes cultural protocol notes external work references export packages manifest metadata ``` Redacted files must either: ```text be replaced by redacted derivatives be withheld from output be excluded from export be marked in the manifest ``` The original restricted file may remain preserved if retention policy requires it. --- ## 33. Public summaries Public summary file area: ```text item_publicsummary ``` Public summary files are not automatically public. They are public only when: ```text parent item is public summary is approved file is not restricted content advisory policy permits public display cultural protocol policy permits public display redaction policy permits public display ``` The name `item_publicsummary` is the canonical File API area for public summaries. --- ## 34. File metadata The module stores file-related metadata in domain tables, not by relying only on Moodle file records. Required metadata may include: ```text uuid source uuid version uuid file role media type mime type duration page count width height size hash rights/license source ownership audience suitability visibility restriction state redaction state provenance createdby modifiedby timecreated timemodified metadata json ``` Moodle File API stores the file. Module tables store semantic meaning. --- ## 35. Rights and source ownership Media source records define ownership and source context. Canonical media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Rights metadata affects: ```text viewing download reuse export public display teaching context derivative generation ``` --- ## 36. File validation Before permanent storage, uploads must be validated for: ```text file size mime type extension malware scan where Moodle/site supports it allowed file types context capability file area itemid rights/source metadata content advisory defaults cultural protocol defaults ``` Invalid files remain in draft state or are rejected. --- ## 37. Forbidden file behavior The plugin must not: ```text store production files in public/media store production files in public/uckk_media store production files in public/assets store binary media in custom DB fields serve files without context checks serve files without policy checks treat URL possession as authorization make derivatives less restricted than originals drop content advisories during export drop cultural protocol restrictions during backup/restore silently overwrite originals silently delete preserved evidence ``` --- ## 38. Required tests Tests must cover: ```text file_area_registry contains all canonical areas pluginfile rejects unknown file areas pluginfile rejects wrong context pluginfile rejects wrong itemid pluginfile enforces media status pluginfile enforces content advisory restrictions pluginfile enforces cultural protocol restrictions media_original stores version-specific files media_thumbnail stores media-level files draft files promote to correct file areas backup includes archive file areas backup includes media file areas backup includes content advisory file areas restore remaps media file areas restore preserves restricted state privacy provider declares all file areas export package uses export_package export manifest uses export_manifest restricted exports exclude unauthorized files ``` --- ## 39. Implementation files Files that implement this specification: ```text lib.php classes/local/file_area_registry.php classes/local/media_file.php classes/local/media_policy.php classes/local/content_policy.php classes/local/export_package.php classes/local/manifest_builder.php classes/privacy/provider.php backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php tests/file_api_test.php tests/privacy_provider_test.php tests/backup_restore_test.php tests/export_test.php ``` --- ## 40. Final rule This document defines the final target behavior for file storage. ```text Moodle File API stores the bytes. mod_uckkarchive owns the meaning, lifecycle, policy, provenance, advisory context, cultural protocol, and export behavior. ``` Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/07_permissions_and_roles.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 72049f6a72772c34e25ac13977c651dfdcd2dcfeab582ed1f83736b3af035fe6 CONTENT_BYTES: 27231 ================================================================================================ # 07 — Permissions and Roles **Path:** `docs/07_permissions_and_roles.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Capabilities, roles, access rules, restricted access, media permissions, content advisory permissions, and server-side policy enforcement for the self-contained UCKK Archive and Media Library Moodle activity module. --- ## 1. Purpose This document defines the final permission and role model for `mod_uckkarchive`. `mod_uckkarchive` is a Moodle-native activity module with a self-contained archive, media library, and content advisory system. The module uses Moodle capabilities as access gates. The module uses internal policy classes as authority enforcement. Canonical rule: ```text Capabilities are gates. Policy classes make final access decisions. Templates, AMD, forms, and controllers do not authorize access. ``` --- ## 2. Permission architecture `mod_uckkarchive` has three permission layers: ```text Moodle capability layer module policy layer record state layer ``` ### 2.1 Moodle capability layer Moodle capabilities answer: ```text Can this user attempt this kind of action in this context? ``` Examples: ```text Can view archive activity? Can add media? Can validate archive item? Can download media? Can review content advisories? ``` ### 2.2 Module policy layer Policy classes answer: ```text Can this specific user perform this specific action on this specific record right now? ``` Policy classes include: ```text classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php ``` ### 2.3 Record state layer Record state affects permissions. Examples: ```text draft submitted active validated published restricted restricted_integrity restricted_cultural contested archived deleted_soft ``` A capability does not override record state. --- ## 3. Canonical policy classes Permission logic must be centralized. ```text classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php ``` ### 3.1 Archive policy `classes/local/archive_policy.php` controls: ```text archive activity access archive item visibility archive item editing archive item validation archive item revision archive item restriction archive item export proof visibility Kristal visibility provenance panel visibility revision history visibility ``` ### 3.2 Media policy `classes/local/media_policy.php` controls: ```text media visibility media creation media metadata editing media deletion media download media original-file access media derivative access media preview access media thumbnail access media versioning media export media collection access restricted media access ``` ### 3.3 Content policy `classes/local/content_policy.php` controls: ```text content advisory visibility content advisory management content marker creation content marker review content tag set management cultural protocol visibility culturally restricted access external work management audience suitability enforcement content review authority ``` --- ## 4. Canonical archive capabilities Archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` | Capability | Purpose | |---|---| | `mod/uckkarchive:addinstance` | Add a UCKK Archive activity to a Moodle course. | | `mod/uckkarchive:view` | View the activity and non-restricted archive records. | | `mod/uckkarchive:additem` | Add archive items, proofs, draft records, and archive submissions. | | `mod/uckkarchive:validateitem` | Validate, reject, contest, restrict, or mark archive review state. | | `mod/uckkarchive:reviseitem` | Revise archive item content, metadata, provenance, visibility, or version state. | | `mod/uckkarchive:viewrestricted` | View archive records restricted by privacy, integrity, or elevated review rules. | | `mod/uckkarchive:export` | Generate archive exports according to export policy. | Archive versioning uses: ```text mod/uckkarchive:reviseitem ``` The module does not use: ```text mod/uckkarchive:versionitem ``` --- ## 5. Canonical media capabilities Media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` | Capability | Purpose | |---|---| | `mod/uckkarchive:viewmedia` | View media library records visible to the user. | | `mod/uckkarchive:addmedia` | Add new media objects and initial media files. | | `mod/uckkarchive:editmedia` | Edit media metadata, tags, source data, advisory visibility, and descriptive fields. | | `mod/uckkarchive:deletemedia` | Soft-delete or retire media according to policy. | | `mod/uckkarchive:downloadmedia` | Download media files when media policy permits it. | | `mod/uckkarchive:versionmedia` | Add new media versions, replacements, derivatives, captions, transcripts, or corrected files. | | `mod/uckkarchive:managemediacollections` | Create and manage media collections and collection membership. | | `mod/uckkarchive:exportmedia` | Export media records, versions, collections, manifests, and allowed files. | | `mod/uckkarchive:viewrestrictedmedia` | View restricted media, culturally restricted media, or elevated-access media when policy permits it. | Media versioning uses: ```text mod/uckkarchive:versionmedia ``` --- ## 6. Canonical content advisory capabilities Content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` | Capability | Purpose | |---|---| | `mod/uckkarchive:viewadvisories` | View content advisories, content warnings, cultural notes, and audience suitability notes visible to the user. | | `mod/uckkarchive:manageadvisories` | Create and edit advisory tags, tag sets, content markers, and advisory metadata. | | `mod/uckkarchive:reviewadvisories` | Review, approve, contest, retire, or confirm content markers and advisory classifications. | | `mod/uckkarchive:viewculturallyrestricted` | View culturally restricted content, markers, protocol notes, or restricted advisory details when policy permits it. | | `mod/uckkarchive:manageexternalworks` | Add and edit external works, foreign media references, source metadata, and locator metadata. | Content advisory rule: ```text A content advisory does not ban media. It defines conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 7. Capability categories Capabilities are grouped into these domains: ```text activity administration archive viewing archive creation archive validation archive revision restricted archive access archive export media viewing media creation media editing media deletion media download media versioning media collection management media export restricted media access content advisory visibility content advisory management content advisory review cultural restriction access external work management ``` --- ## 8. Default Moodle archetypes Capabilities should map to Moodle archetypes conservatively. ### 8.1 Student / participant Typical participant permissions: ```text mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:viewadvisories ``` Participant access remains subject to policy. A participant may not automatically download originals, view restricted media, review advisories, validate archive items, or export packages. ### 8.2 Teacher / mentor Typical teacher or mentor permissions: ```text mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:reviseitem mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories ``` Teacher/mentor authority does not automatically include culturally restricted access or integrity-restricted access. ### 8.3 Editing teacher / manager Typical manager permissions: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:manageexternalworks ``` Culturally restricted access should still be separately controlled. ### 8.4 Administrator Administrators may configure the module and assign roles. Administrative capability does not mean the UI should expose every restricted cultural detail by default. Policy classes may still require explicit access context, audit, or protocol confirmation for sensitive content. --- ## 9. Functional roles The module supports functional roles through Moodle role assignments and capability combinations. Functional role names are descriptive. They do not replace Moodle roles. ### 9.1 Viewer Can view public, course, or permitted archive/media records. Typical capabilities: ```text mod/uckkarchive:view mod/uckkarchive:viewmedia mod/uckkarchive:viewadvisories ``` ### 9.2 Contributor Can add archive items and media. Typical capabilities: ```text mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:viewadvisories ``` ### 9.3 Mentor Can revise items, curate collections, edit metadata, and manage ordinary content advisories. Typical capabilities: ```text mod/uckkarchive:reviseitem mod/uckkarchive:editmedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:manageadvisories ``` ### 9.4 Archivist Can validate records, manage provenance, curate archive memory, export allowed packages, and review records. Typical capabilities: ```text mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:export mod/uckkarchive:editmedia mod/uckkarchive:versionmedia mod/uckkarchive:exportmedia mod/uckkarchive:reviewadvisories ``` ### 9.5 Media librarian Can manage media objects, media versions, media collections, media relations, tags, thumbnails, derivatives, captions, transcripts, and media exports. Typical capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:manageadvisories ``` ### 9.6 Content reviewer Can review content advisories, content markers, cultural notes, and suitability levels. Typical capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories ``` ### 9.7 Cultural protocol reviewer Can view and review culturally restricted markers, protocols, and advisory notes. Typical capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted ``` This role should be assigned deliberately. It should not be bundled automatically into ordinary teacher or manager roles. ### 9.8 External work curator Can create and update external works, source records, foreign media references, and locator metadata. Typical capabilities: ```text mod/uckkarchive:manageexternalworks mod/uckkarchive:manageadvisories mod/uckkarchive:viewadvisories ``` ### 9.9 Integrity reviewer Can view integrity-restricted archive/media records only when integrity-specific policy allows it. Typical capabilities: ```text mod/uckkarchive:viewrestricted mod/uckkarchive:viewrestrictedmedia mod/uckkarchive:viewadvisories ``` Integrity-specific archive features require `tool_uckkintegrity` when case-linked functionality is active. Ordinary archive and media access must not require `tool_uckkintegrity`. --- ## 10. Access decision inputs Every policy decision may use: ```text user id course id course module id context id Moodle capability record owner record creator record modifier record validator record reviewer archive id archive item id media id media uuid media version id external work id content marker id status visibility validation state media state content review state audience suitability restricted flag cultural protocol flag redaction state retention class relation type collection membership source ownership export purpose ``` No single field is sufficient by itself. --- ## 11. Visibility values Canonical visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Compatibility rule: ```text institutional must normalize to institution. ``` Restricted visibility requires additional policy checks. Restricted visibility is not only a display label. --- ## 12. Archive access rules ### 12.1 View archive item To view an archive item, the user must pass: ```text login/session check course module context check mod/uckkarchive:view archive item visibility check archive item status check restricted policy check privacy/redaction policy check ``` ### 12.2 Add archive item To add an archive item, the user must pass: ```text login/session check course module context check mod/uckkarchive:additem archive instance availability check input validation file-area policy ``` ### 12.3 Revise archive item To revise an archive item, the user must pass: ```text login/session check course module context check mod/uckkarchive:reviseitem archive item visibility check revision policy provenance policy restricted policy if applicable ``` ### 12.4 Validate archive item To validate an archive item, the user must pass: ```text login/session check course module context check mod/uckkarchive:validateitem validation policy provenance policy status transition policy restricted policy if applicable ``` ### 12.5 Export archive item To export archive items, the user must pass: ```text login/session check course module context check mod/uckkarchive:export export scope policy visibility policy restricted policy redaction policy retention policy manifest policy ``` --- ## 13. Media access rules ### 13.1 View media To view a media object, the user must pass: ```text login/session check course module context check mod/uckkarchive:viewmedia media visibility check media lifecycle state check content advisory policy restricted media policy privacy/redaction policy ``` ### 13.2 Add media To add media, the user must pass: ```text login/session check course module context check mod/uckkarchive:addmedia media source policy file-area policy metadata validation content advisory default policy ``` ### 13.3 Edit media To edit media metadata, the user must pass: ```text login/session check course module context check mod/uckkarchive:editmedia media ownership or role policy media lifecycle state policy restricted media policy if applicable content advisory policy if changing advisory fields ``` ### 13.4 Delete media To delete media, the user must pass: ```text login/session check course module context check mod/uckkarchive:deletemedia media lifecycle policy retention policy relation policy export history policy restricted media policy ``` Deletion is soft deletion unless policy allows purge. ### 13.5 Download media To download media, the user must pass: ```text login/session check course module context check mod/uckkarchive:downloadmedia media visibility check file-area access check content advisory acknowledgement if required cultural protocol check if required restricted media policy retention/redaction policy ``` ### 13.6 Version media To add a media version, the user must pass: ```text login/session check course module context check mod/uckkarchive:versionmedia media lifecycle policy file-area policy version policy provenance policy content advisory inheritance policy ``` ### 13.7 Export media To export media, the user must pass: ```text login/session check course module context check mod/uckkarchive:exportmedia media export policy file-area policy content advisory policy cultural protocol policy redaction policy manifest policy ``` --- ## 14. Content advisory access rules ### 14.1 View advisories To view content advisories, the user must pass: ```text login/session check course module context check mod/uckkarchive:viewadvisories content marker visibility check content review state check cultural protocol visibility check ``` ### 14.2 Manage advisories To create or edit advisory tags, tag sets, or markers, the user must pass: ```text login/session check course module context check mod/uckkarchive:manageadvisories content policy tag set policy marker locator validation source reference policy ``` ### 14.3 Review advisories To review, approve, contest, retire, or confirm content markers, the user must pass: ```text login/session check course module context check mod/uckkarchive:reviewadvisories review policy cultural protocol policy when applicable human-review requirement audit requirement ``` ### 14.4 View culturally restricted material To view culturally restricted advisory details, the user must pass: ```text login/session check course module context check mod/uckkarchive:viewculturallyrestricted cultural protocol policy audience suitability policy record visibility policy restricted media policy if linked to media redaction policy ``` ### 14.5 Manage external works To manage external works or foreign media references, the user must pass: ```text login/session check course module context check mod/uckkarchive:manageexternalworks source ownership policy external rights metadata validation content advisory policy locator policy ``` --- ## 15. Content advisory acknowledgement Some media or archive records may require acknowledgement before viewing or downloading. Acknowledgement may be required for: ```text strong content advisory restricted content advisory restricted cultural protocol mature audience suitability guided access suitability integrity-sensitive material ``` Acknowledgement records must not replace permission checks. Acknowledgement means: ```text the user has been warned or contextualized ``` Acknowledgement does not mean: ```text the user has unrestricted access the user may export the material the user may bypass cultural protocol the user may redistribute the material ``` --- ## 16. External work permissions External works represent media or works not produced by UCKK. External work records may be visible even when the external media file is not stored by the module. Policy must distinguish: ```text view external work metadata view advisory markers view teaching notes view cultural protocol notes view restricted review notes download local files export reference metadata export copied media files ``` External work permissions must respect: ```text source ownership license metadata rights metadata audience suitability content advisories cultural protocol restrictions redaction rules ``` --- ## 17. Restricted access model Restricted access categories: ```text restricted restricted_integrity restricted_cultural restricted_media restricted_external_work ``` Restricted records require: ```text ordinary capability plus restricted capability plus policy approval ``` Examples: ```text mod/uckkarchive:viewrestricted mod/uckkarchive:viewrestrictedmedia mod/uckkarchive:viewculturallyrestricted ``` Restricted access must be audited. Restricted access must not be inferred only from Moodle manager status. --- ## 18. Cultural protocol model Culturally restricted access is independent from ordinary restricted access. A user may have `viewrestricted` but not `viewculturallyrestricted`. A user may have `viewmedia` but not `viewculturallyrestricted`. Cultural protocol restrictions apply to: ```text media objects media versions content markers external works archive items proofs collections exports manifest details review notes ``` Cultural protocol policy may require: ```text specific role assignment explicit capability human review community permission metadata elder review metadata seasonal/contextual access conditions redaction of protocol details export exclusion ``` --- ## 19. Audience suitability model Audience suitability values: ```text general guided mature restricted restricted_cultural restricted_integrity staff_only ``` Audience suitability affects: ```text viewing download teaching context export search/listing preview display thumbnail display collection inclusion ``` Audience suitability is advisory unless policy marks it restrictive. --- ## 20. Export permission model Archive/media/content exports must check: ```text archive export capability media export capability restricted archive access restricted media access cultural protocol access content advisory policy redaction policy retention policy external work rights metadata manifest policy ``` Export can include: ```text archive item metadata media metadata media files media versions collections relations tags content markers content tag sets content reviews external work metadata manifest.json ``` Export must not include: ```text restricted media files without authority restricted cultural notes without authority third-party copyrighted files when only reference metadata is permitted redacted data private reviewer notes not permitted by policy integrity case procedure records owned by tool_uckkintegrity grades or transcripts ``` --- ## 21. Search and listing permissions Search results must be permission-filtered before rendering. Search must not leak restricted records through: ```text title snippet thumbnail preview caption transcript tag collection membership content advisory marker external work reference count facet autocomplete ``` Restricted records may appear as redacted placeholders only when policy allows. --- ## 22. File download permissions File downloads pass through the `pluginfile` handler in `lib.php`. The handler must check: ```text component = mod_uckkarchive file area context item id record existence record visibility record status Moodle capability archive/media/content policy restricted status redaction status retention status ``` File URL possession is not authority. --- ## 23. Service permissions Every external service must define and enforce: ```text parameters context resolution login requirement capability checks record lookup policy checks return filtering warnings exceptions audit event if state changes ``` Services must not return raw restricted data to be hidden client-side. Filtering happens server-side before response construction. --- ## 24. UI permissions UI components may show or hide actions based on permission-filtered data. UI components must not decide access. Templates and AMD modules may use flags such as: ```text canview canedit canvalidate canrevise candownload canexport canreviewadvisory canviewrestricted canviewcultural ``` Those flags come from server-side policy. --- ## 25. Backup and restore permissions Backup/restore preserves records and permissions metadata. Restore must preserve: ```text visibility restricted flags cultural protocol flags content advisory tags content markers review states redaction state retention class relations collections source ownership ``` Restore must not make restricted data public. Restore must not grant new authority. --- ## 26. Privacy permissions Privacy export and deletion must respect: ```text user data ownership third-party data restricted cultural protocol notes integrity-sensitive material external work metadata media files review notes redaction state retention class institutional preservation rules ``` A privacy export request is not a permission bypass. --- ## 27. Role preset guidance The plugin may provide role preset documentation. Role presets must not be hard-coded as authority. Suggested presets: ```text viewer contributor mentor archivist media_librarian content_reviewer cultural_protocol_reviewer external_work_curator integrity_reviewer ``` Moodle site administrators decide actual role assignments. --- ## 28. Denial behavior When access is denied, the module should avoid leaking sensitive information. Possible denial responses: ```text not found access denied restricted requires review requires cultural permission requires content advisory acknowledgement not exportable redacted ``` The exact response depends on policy. Restricted records should not reveal more than policy permits. --- ## 29. Audit behavior The module should audit successful state-changing operations. Audited actions include: ```text archive item created archive item revised archive item validated archive item exported media created media updated media deleted_soft media version created media downloaded when restricted media exported media collection created content marker created content marker reviewed external work created restricted record viewed when audit policy requires it ``` Audit events must not expose restricted content or redacted details. --- ## 30. Implementation files Permission definitions: ```text db/access.php ``` Service declarations: ```text db/services.php ``` Policy classes: ```text classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php ``` File access: ```text lib.php classes/local/file_area_registry.php classes/local/media_file.php ``` Privacy: ```text classes/privacy/provider.php ``` Backup/restore: ```text backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` Tests: ```text tests/archive_test.php tests/media_library_test.php tests/content_advisory_test.php tests/file_api_test.php tests/privacy_provider_test.php tests/services_test.php tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` --- ## 31. Final permission rule ```text Moodle capabilities open the gate. Archive, media, and content policies decide the actual access. Record state, visibility, validation, restriction, redaction, retention, cultural protocol, and content advisory rules remain enforceable at all times. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/08_archive_workflows.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 271940dfcaff4434ac9b56a5dde3683c299e3538a63ae7f1a27e117c2bc37ac2 CONTENT_BYTES: 25484 ================================================================================================ # 08 — Archive Workflows **Path:** `docs/08_archive_workflows.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Archive item workflows for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Purpose This document defines the final archive workflows for `mod_uckkarchive`. The archive workflow layer governs how archive items are created, submitted, reviewed, validated, revised, restricted, contested, invalidated, archived, exported, and connected to media, provenance, Kristals, proofs, content advisories, external works, and Moodle contexts. `mod_uckkarchive` is: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` The archive workflow does not replace Moodle gradebook, course enrolment, Assembly authority, challenge authority, integrity case authority, or institutional reporting authority. --- ## 2. Workflow ownership `mod_uckkarchive` owns workflows for: ```text archive item creation archive item draft saving archive item submission archive item review archive item validation archive item revision archive item restriction archive item contestation archive item invalidation archive item archival archive item export archive-media linking archive-provenance linking archive-content advisory linking archive-external work reference linking ``` `mod_uckkarchive` does not own workflows for: ```text grading transcripts course enrolment institutional registry state challenge completion authority Assembly decision authority integrity case findings sanctions appeals institutional reporting authority ``` The archive may preserve traces, evidence, references, or snapshots from external domains. Preservation does not transfer authority. --- ## 3. Archive item identity Each archive item has two identifiers: ```text id = local Moodle database primary key uuid = stable portable archive identity ``` The `id` is used internally by Moodle database operations. The `uuid` is used for: ```text export restore duplication cross-site portability manifest references external package references long-term archive identity ``` An archive item must not rely on a Moodle database `id` as its only durable identity. --- ## 4. Archive item status model Canonical archive item statuses: ```text draft submitted under_review validated published restricted contested invalidated superseded archived ``` Status meaning: | Status | Meaning | |---|---| | `draft` | Item exists but is not formally submitted. | | `submitted` | Item was submitted for review, validation, or preservation. | | `under_review` | Item is actively being reviewed. | | `validated` | Item has passed human validation. | | `published` | Item is visible according to its visibility policy. | | `restricted` | Item is preserved but access is restricted. | | `contested` | Item remains preserved but is under dispute. | | `invalidated` | Item is preserved as invalidated memory, not deleted silently. | | `superseded` | Item remains preserved but is replaced by a newer item or revision. | | `archived` | Item is preserved for long-term memory and normal editing is closed. | --- ## 5. Validation state model Canonical validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Validation state is separate from visibility. An item may be: ```text validated but private validated but restricted published but later contested archived but not public invalidated but still preserved ``` Validation rule: ```text Validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. ``` --- ## 6. Visibility model Canonical visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Visibility controls who may see the item. Visibility does not by itself grant permission to: ```text download restricted files view culturally restricted content view integrity-restricted material export records revise records validate records delete records ``` All visibility decisions are enforced by policy classes and Moodle capabilities. --- ## 7. Core workflow map Canonical archive item workflow: ```text draft → submitted → under_review → validated → published → archived ``` Exceptional workflows: ```text submitted → draft under_review → submitted under_review → contested validated → contested validated → superseded validated → invalidated published → contested published → restricted published → superseded published → archived restricted → archived contested → human_reviewed contested → invalidated contested → validated invalidated → archived superseded → archived ``` Forbidden silent transitions: ```text published → draft validated → unverified restricted_integrity → public restricted_cultural → public invalidated → verified contested → published archived → published ``` If an exceptional transition is allowed, it must create a revision record with an explicit reason and actor. --- ## 8. Draft workflow Draft creation begins when a user creates or saves an archive item before formal submission. Draft workflow: ```text new request → create draft archive item → assign uuid → set status = draft → set validationstate = unverified → set default visibility → save metadata → save draft files through Moodle File API → create initial revision record ``` Draft requirements: ```text draft items must have a uuid draft items must have an owner or createdby user draft items must have context draft files must remain within Moodle File API drafts must not be public drafts must not be exported as official archive packages ``` Draft access: ```text creator users with edit authority users with validation authority when submitted for review ``` Draft deletion may be allowed when the item has no institutional preservation dependency. --- ## 9. Submission workflow Submission begins when a draft is formally submitted. Submission workflow: ```text draft → submitted → create revision → lock submitted fields when required → notify or expose to reviewers → make item eligible for review ``` Submission requirements: ```text required title required item type required context required provenance baseline required visibility baseline required createdby required uuid required status transition reason when configured ``` Submission does not equal validation. Submission does not equal publication. Submission does not create grades. --- ## 10. Review workflow Review begins when a submitted item is taken into review. Review workflow: ```text submitted → under_review → provenance review → media link review → content advisory review → cultural protocol review where applicable → privacy review where applicable → validation decision ``` Review may produce: ```text validation revision request restriction content advisory marker cultural protocol note contestation invalidation archive note ``` Review requires human accountability. AI may assist with summaries, suggestions, or candidate tags, but human review remains final. --- ## 11. Validation workflow Validation confirms that an archive item is reliable enough for its intended archive role. Validation workflow: ```text under_review → human_reviewed → verified → validated ``` Validation must record: ```text validator user id validation time validation state validation reason provenance state visibility state restriction state content advisory state revision id ``` Validation may also update: ```text visibility public summary content advisory markers media relations provenance hash retention class redaction state ``` Validation uses capability: ```text mod/uckkarchive:validateitem ``` Validation creates event: ```text mod_uckkarchive\event\archive_item_validated ``` --- ## 12. Revision workflow Revision changes archive content, metadata, provenance, media links, validation state, visibility, or policy-relevant fields. Revision workflow: ```text load item → check context → check visibility → require reason → apply change → increment version number when meaningful → create uckkarchive_rev → update provenance hash when relevant → trigger revision event ``` Revision uses capability: ```text mod/uckkarchive:reviseitem ``` There is no current archive item capability named: ```text mod/uckkarchive:versionitem ``` Archive item versioning is controlled by: ```text mod/uckkarchive:reviseitem ``` Revision creates event: ```text mod_uckkarchive\event\archive_item_revised ``` --- ## 13. Media linking workflow Archive items may link to first-class media objects. Media is not only an archive item attachment. Media is represented by: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` Media linking workflow: ```text select archive item → select media object → check archive access → check media access → create relation → create revision record → update provenance when relevant → refresh archive item view ``` Common relation types: ```text belongs_to_item is_proof_for is_source_for references contains_content_marker ``` Media files remain in media file areas. Archive item files remain in archive file areas. The module must not duplicate files unnecessarily. --- ## 14. Proof workflow Proofs are evidence records connected to archive items, media, challenges, validation, or integrity-related preservation. Proof workflow: ```text create proof → link proof to archive item → link proof to media when applicable → save proof files through Moodle File API → record provenance → set visibility/restriction → create revision ``` Proofs may be associated with: ```text challenge evidence portfolio evidence validation evidence integrity evidence Assembly evidence course work evidence ``` Proof preservation does not create gradebook authority. Proof preservation does not create integrity case authority. Proof files use: ```text proof_files ``` Proof access is enforced through archive policy and restricted-access checks. --- ## 15. Kristal workflow Kristals are archive-connected memory or knowledge objects. Kristal workflow: ```text create Kristal → link to archive item → link to media where applicable → link to provenance → validate when required → revise when updated → preserve as archive memory ``` Kristals may link to: ```text archive items media objects proofs content advisories external works collections provenance records ``` Kristal files use: ```text kristal_files ``` --- ## 16. Content advisory workflow Content advisories are first-class governance records. They describe suitability, sensitivity, cultural protocol, and access conditions. Content advisory workflow: ```text identify content concern → choose content tag → create content marker → attach locator → link to media, archive item, media version, or external work → set audience suitability → set advisory severity → review marker → approve, contest, or retire marker ``` Content advisory tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review ``` Content advisory does not automatically ban media. It provides responsible warning, teaching context, suitability guidance, restriction, review, or cultural protocol. --- ## 17. Content marker workflow Content markers link advisories to precise locations. A marker may point to: ```text media object media version archive item external work manual reference ``` Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Examples: ```text Movie Maïna -> sexual_violence -> 01:12:30-01:15:10 Book The Body Keeps the Score -> sexual_violence -> page 42-45 PDF -> culturally_sensitive -> page 7 Audio -> grief_or_mourning -> 00:08:12-00:09:40 ``` A content marker must include enough locator information to be useful without storing unauthorized copies of external content. --- ## 18. External work workflow External works are works not produced by UCKK that may be referenced, taught, reviewed, tagged, or connected to archive/media records. External work workflow: ```text create external work record → record bibliographic/source metadata → record source ownership → add content markers → add advisory tags → link to archive item or media object when relevant → preserve reference without claiming ownership ``` External work table: ```text uckkarchive_external_work ``` External work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External/foreign media rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` --- ## 19. Media source workflow Media source records define origin and rights context. Media source table: ```text uckkarchive_media_source ``` Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Media source workflow: ```text create or update media source → record source ownership → record rights/usage category → link media object or external work → update provenance → update export manifest eligibility ``` --- ## 20. Cultural protocol workflow Cultural protocol is part of the content advisory system. Cultural protocol tags may include: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Cultural protocol workflow: ```text identify cultural protocol concern → create content marker → attach cultural protocol tag → set restricted_cultural visibility when needed → require human review → record review decision → enforce access policy ``` Cultural protocol access requires policy checks beyond ordinary visibility. AI cannot approve cultural protocol access. --- ## 21. Restriction workflow Restriction limits access while preserving records. Restriction workflow: ```text identify restriction need → set visibility = restricted, restricted_integrity, or restricted_cultural → record reason → create revision → update policy metadata → update file access behavior → update export eligibility ``` Restriction reasons may include: ```text privacy integrity sensitivity cultural protocol minor safety content advisory severity copyright or external rights unvalidated provenance contested record ``` Restricted items remain preserved unless deletion or anonymisation is explicitly allowed. --- ## 22. Contestation workflow Contestation records disagreement, uncertainty, objection, review challenge, or cultural/provenance concern. Contestation workflow: ```text validated or published item → contested → record contestation reason → preserve original state → create revision → notify/reveal to reviewers → review evidence → validate, restrict, supersede, invalidate, or archive ``` Contested records must not be silently overwritten. Contestation may apply to: ```text archive item media metadata media relation content advisory marker external work reference provenance claim validation decision public summary ``` --- ## 23. Invalidation workflow Invalidation preserves the fact that something was rejected, superseded, false, unsafe, or unsuitable as originally stated. Invalidation workflow: ```text review contested or validated record → determine invalidation → record reason → preserve previous revision → set validationstate = invalidated → set status = invalidated → restrict or archive as needed ``` Invalidated records must not be silently deleted when they have institutional memory value. Invalidated records may be hidden from ordinary browsing while preserved for audit, provenance, and review. --- ## 24. Supersession workflow Supersession records that a newer or corrected record replaces an older one. Supersession workflow: ```text create or select replacement item → link previous item → set previous item status = superseded → create revision on both records → update relation/provenance → update export manifest behavior ``` Superseded records remain preserved. Supersession does not erase the older record. --- ## 25. Archival workflow Archival closes active workflow while preserving memory. Archival workflow: ```text validated, invalidated, superseded, restricted, or contested record → archived → lock ordinary editing → preserve provenance → preserve revision history → preserve content advisory markers → preserve media relations → preserve export eligibility policy ``` Archived does not mean public. Archived does not mean unrestricted. Archived does not mean deleted. --- ## 26. Export workflow Archive exports are generated from archive/media-owned records. Export workflow: ```text select export scope → preview included records → apply visibility policy → apply restricted policy → apply content advisory policy → apply cultural protocol policy → apply redaction policy → create export package → create manifest.json → save export files through Moodle File API → trigger event ``` Export package file area: ```text export_package ``` Export manifest file area: ```text export_manifest ``` Export must include metadata needed for portability and interpretation. Export must not bypass restrictions, content advisories, cultural protocol, redaction, privacy, or rights constraints. --- ## 27. Privacy workflow Privacy workflow applies to all archive/media/content-advisory records containing user-linked data. Privacy workflow includes: ```text identify user-linked records export user data delete allowed draft data anonymise where required redact third-party sensitive content preserve institutional memory where allowed preserve restricted records where required ``` Privacy provider must cover: ```text archive items proofs Kristals provenance revisions exports media objects media versions media collections media relations media tags content tags content tag sets content markers content reviews external works where user-linked media source records where user-linked files ``` --- ## 28. Backup and restore workflow Backup preserves module-owned archive/media/content-advisory state. Backup includes: ```text archive items proofs Kristals provenance revisions exports media objects media versions media relations media tags media collections media collection items content tags content tag sets content markers content reviews external works media source records files ``` Restore reconstructs module-owned records only. Restore must not create: ```text grades transcripts course enrolment authority Assembly authority challenge workflow authority integrity case authority institutional reporting authority ``` Restore must preserve: ```text uuid identity visibility restriction state content advisory state cultural protocol state validation state provenance revision history relations collections export metadata ``` --- ## 29. Event workflow Archive workflows trigger Moodle events after successful state changes. Canonical archive events: ```text archive_viewed archive_item_created archive_item_validated archive_item_revised archive_item_exported ``` Related media/content events: ```text media_created media_updated media_version_created media_collection_created media_exported content_marker_created content_marker_reviewed external_work_created ``` Event rules: ```text events audit successful state changes events include context and object identifiers events do not expose raw restricted content events do not expose redacted details events do not expose private cultural protocol notes ``` --- ## 30. Service workflow rules Every workflow exposed through AJAX or web service must use `classes/external`. Every service must: ```text require login resolve context validate parameters check capabilities call policy classes call local domain classes return permission-filtered data avoid leaking restricted metadata ``` Services must not duplicate workflow policy. Services must call: ```text classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php ``` --- ## 31. UI workflow rules The UI may show: ```text status visibility validation state media links content advisory badges cultural protocol badges review state available actions warnings export eligibility ``` The UI must not decide: ```text authority validation restriction cultural protocol access download access export access privacy access redaction access ``` All UI actions must call server-side services. --- ## 32. Scheduled maintenance workflows Scheduled tasks may handle: ```text media derivative generation media thumbnail generation export package generation expired export purge media search rebuild content marker index rebuild pending item validation maintenance ``` Scheduled tasks must reuse local domain classes and policies. Scheduled tasks must not bypass access, restriction, redaction, or content advisory rules for generated outputs. --- ## 33. Workflow capability map Archive workflow capabilities: | Workflow | Capability | |---|---| | View archive | `mod/uckkarchive:view` | | Add archive item | `mod/uckkarchive:additem` | | Validate archive item | `mod/uckkarchive:validateitem` | | Revise archive item | `mod/uckkarchive:reviseitem` | | View restricted item | `mod/uckkarchive:viewrestricted` | | Export archive item | `mod/uckkarchive:export` | Media workflow capabilities: | Workflow | Capability | |---|---| | View media | `mod/uckkarchive:viewmedia` | | Add media | `mod/uckkarchive:addmedia` | | Edit media | `mod/uckkarchive:editmedia` | | Delete media | `mod/uckkarchive:deletemedia` | | Download media | `mod/uckkarchive:downloadmedia` | | Add media version | `mod/uckkarchive:versionmedia` | | Manage collections | `mod/uckkarchive:managemediacollections` | | Export media | `mod/uckkarchive:exportmedia` | | View restricted media | `mod/uckkarchive:viewrestrictedmedia` | Content advisory workflow capabilities: | Workflow | Capability | |---|---| | View advisories | `mod/uckkarchive:viewadvisories` | | Manage advisories | `mod/uckkarchive:manageadvisories` | | Review advisories | `mod/uckkarchive:reviewadvisories` | | View culturally restricted material | `mod/uckkarchive:viewculturallyrestricted` | | Manage external works | `mod/uckkarchive:manageexternalworks` | Capabilities are gates, not complete authority. Policy classes remain authoritative. --- ## 34. Required local classes Archive workflows depend on: ```text classes/local/archive_item.php classes/local/archive_policy.php classes/local/proof.php classes/local/kristal.php classes/local/provenance.php classes/local/revision.php ``` Media workflows depend on: ```text classes/local/media.php classes/local/media_policy.php classes/local/media_version.php classes/local/media_collection.php classes/local/media_relation.php classes/local/media_tag.php classes/local/media_file.php ``` Content advisory workflows depend on: ```text classes/local/content_tag.php classes/local/content_tag_set.php classes/local/content_marker.php classes/local/content_review.php classes/local/content_policy.php classes/local/external_work.php classes/local/media_source.php ``` Shared workflow infrastructure: ```text classes/local/context_resolver.php classes/local/file_area_registry.php classes/local/manifest_builder.php classes/local/metadata_validator.php classes/local/uuid.php ``` --- ## 35. Final workflow rule ```text Archive workflows preserve memory. Media workflows manage reusable media objects. Content advisory workflows describe responsible access and suitability. Provenance workflows explain origin. Validation workflows record human trust. Revision workflows preserve change. Restriction workflows protect sensitive records. Export workflows package only what policy allows. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/09_media_workflows.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 93a97ad36d67d8f1588b13b1424107f96414c3e6749414c38d42e5f4b26d4ff8 CONTENT_BYTES: 29864 ================================================================================================ # 09 — Media Workflows **Path:** `docs/09_media_workflows.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Media library workflows for the self-contained UCKK Archive and Media Library Moodle activity module. --- ## 1. Purpose This document defines the final target media workflows for `mod_uckkarchive`. `mod_uckkarchive` is a Moodle-native activity module with a self-contained archive, media library, and content advisory system. Media is a first-class domain object. Media is not only an archive item attachment. Media is not stored in unmanaged public folders. Media is not stored directly as binary data in custom database fields. Media files are stored through Moodle File API. Media identity, metadata, versions, collections, relations, content advisories, cultural protocol markers, source records, and export identity are stored in `mod_uckkarchive` tables. --- ## 2. Core workflow rule Canonical formula: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` Media workflows must use Moodle for: ```text course module context users roles capabilities File API Privacy API Backup API Restore API External Services API events settings language strings scheduled tasks ``` Media workflows are owned internally by: ```text classes/local/media.php classes/local/media_file.php classes/local/media_policy.php classes/local/media_version.php classes/local/media_collection.php classes/local/media_relation.php classes/local/media_tag.php classes/local/media_search.php classes/local/media_source.php classes/local/content_marker.php classes/local/content_policy.php classes/local/content_review.php classes/local/content_tag.php classes/local/content_tag_set.php classes/local/external_work.php ``` Controllers, templates, and AMD modules do not own media policy. --- ## 3. Media object model Every managed media object is represented by: ```text uckkarchive_media ``` Every media object has: ```text id uuid archiveid courseid cmid contextid title description mediatype mimetype status visibility audiencesuitability sourceid currentversionid createdby modifiedby timecreated timemodified metadata ``` Identifier rule: ```text id = local Moodle database primary key uuid = stable portable object identity ``` UUIDs are required for: ```text backup restore export import duplication cross-site portability external manifest references media relation graphs ``` --- ## 4. Media lifecycle Canonical media states: ```text draft submitted active restricted superseded archived deleted_soft ``` Lifecycle meaning: | State | Meaning | |---|---| | `draft` | Media record exists but is not submitted for use. | | `submitted` | Media was submitted and awaits review, metadata completion, or validation. | | `active` | Media is usable according to visibility and policy. | | `restricted` | Media exists but requires additional capability, cultural protocol, integrity access, or guided context. | | `superseded` | Media remains preserved but is no longer the current version or preferred item. | | `archived` | Media is retained for memory, evidence, or historical reasons. | | `deleted_soft` | Media is removed from normal use but preserved for retention, audit, or recovery policy. | Lifecycle rule: ```text File existence is not media availability. Media status controls usability. Visibility controls access. Policy controls download and export. Content advisories describe suitability, cultural protocol, and access conditions. Retention controls deletion. ``` --- ## 5. Media creation workflow Media creation begins through: ```text media.php classes/form/media_form.php classes/external/add_media.php classes/local/media.php classes/local/media_file.php ``` Creation workflow: ```text 1. User opens media library or archive item media panel. 2. User selects add/upload/reference media. 3. Moodle context and capability are checked. 4. Media form collects metadata and file/reference information. 5. File is uploaded to Moodle draft area or external work reference is recorded. 6. Service validates input. 7. Media policy checks permission and workflow state. 8. Media UUID is generated. 9. uckkarchive_media record is created. 10. Initial uckkarchive_media_version record is created when a file is stored. 11. File is promoted to the correct Moodle File API area. 12. Provenance is recorded. 13. Content advisory defaults are applied. 14. Event media_created is triggered. 15. Permission-filtered media card is returned. ``` Required capability: ```text mod/uckkarchive:addmedia ``` Required policy checks: ```text context access course module visibility media library availability upload permission source permission file type permission size limit visibility selection cultural protocol constraints privacy constraints ``` --- ## 6. Media source workflow Every media object has a source classification. Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Media source data is stored in: ```text uckkarchive_media_source classes/local/media_source.php ``` Source workflow: ```text 1. User selects media source type. 2. User records creator, owner, license, URL, citation, or origin statement. 3. Media source policy validates the source category. 4. External works are linked when media references a non-UCKK work. 5. Provenance is recorded. 6. Source metadata is included in backup, restore, privacy export, and export manifest. ``` Source rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` --- ## 7. External work workflow Works not produced by UCKK are represented by: ```text uckkarchive_external_work classes/local/external_work.php ``` External work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External work workflow: ```text 1. User selects create or link external work. 2. User enters title, creator, year, publisher/source, URL/identifier, rights note, and citation. 3. External work UUID is generated. 4. Work metadata is stored without copying protected content unless permitted. 5. Content markers can be attached to the external work. 6. External work can be related to internal media, archive items, collections, or course contexts. 7. Event external_work_created is triggered. ``` External work services: ```text classes/external/get_external_works.php classes/external/get_external_work.php classes/external/add_external_work.php classes/external/update_external_work.php ``` Required capability: ```text mod/uckkarchive:manageexternalworks ``` --- ## 8. Media file workflow Media files are stored through Moodle File API. Component: ```text mod_uckkarchive ``` Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` File-area ownership: | File area | Purpose | |---|---| | `media_original` | Original uploaded or preserved file. | | `media_preview` | Preview-optimized representation. | | `media_thumbnail` | Thumbnail image or preview still. | | `media_derivative` | Generated derivative, compressed version, resized image, or converted format. | | `media_caption` | Caption file. | | `media_transcript` | Transcript file. | | `media_attachment` | Related supporting file. | File workflow: ```text 1. User uploads file to Moodle draft area. 2. Service validates media type, size, source metadata, and context. 3. Media policy checks upload authority. 4. File is saved to the canonical media file area. 5. Hash, size, MIME type, and file metadata are stored in media version metadata. 6. Media version becomes current version unless policy prevents activation. 7. Derivative and thumbnail tasks are queued when applicable. ``` Forbidden storage: ```text No production archive/media files in unmanaged public folders. No binary media files directly in custom database fields. No direct public file URLs as authority. ``` --- ## 9. Media version workflow Media versioning is first-class. Media versions are stored in: ```text uckkarchive_media_version classes/local/media_version.php ``` Media versioning uses: ```text mod/uckkarchive:versionmedia ``` Version workflow: ```text 1. User requests add media version. 2. Service checks context and mod/uckkarchive:versionmedia. 3. Existing media object is loaded. 4. Media policy checks edit/version authority. 5. New file or metadata revision is submitted. 6. New media version UUID is generated. 7. File is stored in the correct File API area. 8. Hash, MIME type, size, duration/page count, and technical metadata are recorded. 9. Previous current version remains preserved. 10. Current version pointer is updated when policy allows. 11. Provenance and revision records are created. 12. Event media_version_created is triggered. ``` Versioning rule: ```text Media files are not silently overwritten. Every replacement, derivative, transcript, caption, or major metadata correction creates a version or derivative record. ``` --- ## 10. Derivative and thumbnail workflow Media derivatives and thumbnails are generated through scheduled tasks: ```text classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php ``` Derivative workflow: ```text 1. Media version is created or updated. 2. Task queue marks derivative generation required. 3. Scheduled task loads media and current version. 4. Media policy checks that derivative generation is permitted. 5. Derivative file is generated. 6. Generated file is stored in media_derivative or media_preview. 7. Thumbnail is stored in media_thumbnail. 8. Metadata records derivative relation to the source version. 9. Event or audit record is created when relevant. ``` Derivative relation type: ```text is_derivative_of ``` Derivative rule: ```text The original file remains preserved. Derivatives and thumbnails never replace the original. ``` --- ## 11. Caption and transcript workflow Caption and transcript files are stored as media-related files. File areas: ```text media_caption media_transcript ``` Workflow: ```text 1. User adds caption or transcript file to a media object or version. 2. Service checks edit or version authority. 3. File is validated. 4. Caption/transcript language and format are recorded. 5. File is stored through Moodle File API. 6. Media version or media metadata is updated. 7. Provenance is recorded. 8. Content advisories may reference transcript/page/time locators. ``` Rules: ```text Captions and transcripts may have their own visibility and restriction metadata. Transcript text can contain sensitive content and must follow privacy and content advisory rules. ``` --- ## 12. Media collection workflow Media collections are first-class. Collections are stored in: ```text uckkarchive_media_collection uckkarchive_media_collection_item classes/local/media_collection.php ``` Collection workflow: ```text 1. User creates media collection. 2. Service checks mod/uckkarchive:managemediacollections. 3. Collection UUID is generated. 4. Collection title, description, visibility, purpose, and metadata are stored. 5. Media items are added to the collection. 6. Ordering and grouping metadata are stored. 7. Event media_collection_created is triggered. ``` Collection examples: ```text course pack Kristal source pack challenge evidence pack assembly record pack public media set restricted proof bundle external work study set cultural protocol set ``` Collection rule: ```text Collections group media. Collections do not duplicate media files. Collections do not override media-level restrictions. ``` --- ## 13. Media relation workflow Media relations are stored in: ```text uckkarchive_media_relation classes/local/media_relation.php ``` Canonical relation types: ```text belongs_to_item belongs_to_kristal belongs_to_collection is_derivative_of is_translation_of is_excerpt_of is_proof_for is_source_for replaces references duplicates references_external_work contains_content_marker ``` Relation workflow: ```text 1. User or system creates a relation between media, archive item, Kristal, collection, external work, or content marker. 2. Service checks relation authority. 3. Relation type is validated. 4. Source and target object existence is verified. 5. Relation is stored with UUID and metadata. 6. Provenance is recorded. 7. Relation graph becomes available to media search and export manifest. ``` Relation rule: ```text Relations describe graph meaning. Relations do not transfer ownership to external plugins or external rights holders. ``` --- ## 14. Media tagging workflow Media tags are stored in: ```text uckkarchive_media_tag classes/local/media_tag.php ``` Media tag workflow: ```text 1. User adds tag to media object. 2. Service checks edit authority. 3. Tag key is normalized. 4. Tag type is validated. 5. Tag is stored with source and provenance. 6. Search index is updated. ``` Media tags are used for: ```text topic format course use collection use language region pedagogical theme source category review state ``` Content advisory tags are not stored as ordinary media tags. Content advisory tags belong to: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review ``` --- ## 15. Content advisory workflow Content advisories describe suitability, cultural protocol, and access conditions. Required tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review ``` Required local classes: ```text classes/local/content_tag.php classes/local/content_tag_set.php classes/local/content_marker.php classes/local/content_review.php classes/local/content_policy.php ``` User-facing labels: ```text content advisory content warning cultural advisory cultural protocol audience suitability trigger warning ``` Architecture rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 16. Content tag workflow Content tags define reusable advisory and cultural protocol vocabulary. Content tags are stored in: ```text uckkarchive_content_tag ``` Content tag examples: ```text sexual_violence violence racism colonial_violence death self_harm substance_use nudity explicit_language culturally_sensitive sacred_content ceremonial_content restricted_knowledge grief_or_mourning requires_context not_for_children ``` Content tag workflow: ```text 1. Authorized user creates or edits content tag. 2. Tag key, label, description, severity, category, and cultural protocol flag are stored. 3. Tag can be assigned to a tag set. 4. Tag becomes available for content markers and reviews. ``` Required capability: ```text mod/uckkarchive:manageadvisories ``` --- ## 17. Content tag set workflow Tag sets group advisory tags into reusable vocabularies. Tag sets are stored in: ```text uckkarchive_content_tag_set ``` Examples: ```text general_advisories cultural_protocols classroom_suitability integrity_sensitive youth_access ``` Tag set workflow: ```text 1. Authorized user creates tag set. 2. Tags are added to the set. 3. Tag set is assigned purpose and visibility. 4. Tag set becomes available for course, collection, media, or archive context. ``` Rule: ```text Tag sets organize vocabulary. Tag sets do not themselves restrict access unless content policy uses them to evaluate access conditions. ``` --- ## 18. Content marker workflow Content markers link an advisory tag to a location inside media, archive material, or an external work. Content markers are stored in: ```text uckkarchive_content_marker ``` Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Content marker examples: ```text Movie Maïna -> sexual_violence -> 01:12:30-01:15:10 Book The Body Keeps the Score -> sexual_violence -> page 42-45 PDF -> culturally_sensitive -> page 7 Audio -> grief_or_mourning -> 00:08:12-00:09:40 Website -> colonial_violence -> url_fragment #section-3 ``` Content marker workflow: ```text 1. User opens media, archive item, or external work advisory panel. 2. User selects advisory tag. 3. User selects locator type. 4. User enters locator value or range. 5. User enters note, teaching context, or cultural protocol context. 6. Marker is saved as draft or pending review. 7. Review workflow approves, contests, retires, or restricts marker. ``` Required services: ```text classes/external/get_content_markers.php classes/external/add_content_marker.php classes/external/update_content_marker.php classes/external/delete_content_marker.php classes/external/review_content_marker.php ``` --- ## 19. Content review workflow Content review records human judgment over markers, advisories, cultural protocols, and suitability. Content reviews are stored in: ```text uckkarchive_content_review ``` Review states: ```text draft pending_review reviewed approved contested retired ``` Review workflow: ```text 1. Marker is submitted for review. 2. Reviewer opens advisory panel. 3. Reviewer checks source, locator, advisory tag, note, and cultural protocol. 4. Reviewer sets review state. 5. Reviewer may set audience suitability or restricted cultural visibility. 6. Review record is saved with actor, timestamp, state, and rationale. 7. Event content_marker_reviewed is triggered. ``` AI rule: ```text AI may suggest tags or markers. AI cannot approve content advisories. AI cannot approve cultural protocol access. Human review is required before advisory status becomes approved. ``` --- ## 20. Cultural protocol workflow Cultural protocol handling uses content advisory infrastructure. Cultural protocol tag examples: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Cultural protocol workflow: ```text 1. User or reviewer identifies culturally sensitive content. 2. Content marker is created. 3. Cultural protocol tag is applied. 4. Marker is reviewed by authorized reviewer. 5. Visibility may be set to restricted_cultural. 6. Access policy enforces view/download/export restrictions. 7. Advisory panel explains access conditions to authorized users. ``` Required capability for restricted cultural material: ```text mod/uckkarchive:viewculturallyrestricted ``` Cultural protocol rule: ```text Restricted cultural material must not become public through search, export, backup preview, course display, media thumbnails, or derivative generation. ``` --- ## 21. Audience suitability workflow Audience suitability values: ```text general guided mature restricted restricted_cultural restricted_integrity staff_only ``` Suitability workflow: ```text 1. Media or content marker is assigned suitability level. 2. Policy checks whether current user can view the media, advisory, derivative, thumbnail, download, or export. 3. UI displays advisory when appropriate. 4. Restricted suitability prevents ordinary access. 5. Export manifest includes suitability values. ``` Rule: ```text Audience suitability is descriptive and policy-relevant. It does not replace Moodle capabilities. ``` --- ## 22. Media search workflow Search is handled by: ```text classes/local/media_search.php classes/task/rebuild_media_search.php ``` Searchable dimensions: ```text title description media type MIME type source type creator license tags collections relations status visibility audience suitability content advisory tags external work metadata provenance ``` Search rule: ```text Search results are permission-filtered. Restricted records are not leaked through counts, facets, thumbnails, previews, or snippets. ``` --- ## 23. Media display workflow Media display is handled by: ```text media.php classes/output/media_library.php classes/output/media_card.php classes/output/media_collection.php classes/output/media_version_list.php templates/media_library.mustache templates/media_card.mustache templates/media_collection.mustache templates/media_version_list.mustache templates/content_advisory_panel.mustache ``` Display workflow: ```text 1. Controller resolves course, module, archive, context, and page state. 2. Policy filters accessible media. 3. Output classes format media data. 4. Advisory panel data is attached when applicable. 5. Templates render filtered data. 6. AMD modules enhance interaction. ``` Display rule: ```text Templates receive pre-filtered render data. Templates do not decide authority. Thumbnails, previews, advisories, tags, and snippets must be filtered before rendering. ``` --- ## 24. Media download workflow Download is handled through: ```text lib.php uckkarchive_pluginfile() classes/local/media_policy.php classes/local/media_file.php ``` Download workflow: ```text 1. User requests media file. 2. Moodle pluginfile handler resolves context, file area, item id, and file. 3. Media object or version is loaded. 4. Media policy checks view/download authority. 5. Restricted, cultural, integrity, retention, and redaction rules are applied. 6. File is served only if all checks pass. ``` Download capabilities: ```text mod/uckkarchive:downloadmedia mod/uckkarchive:viewrestrictedmedia mod/uckkarchive:viewculturallyrestricted ``` Download rule: ```text A direct file URL is never sufficient authority. ``` --- ## 25. Media export workflow Media can be exported as: ```text single media export media collection export archive item with related media export external work reference export content advisory package export ``` Export services: ```text classes/external/export_media.php classes/external/export_collection.php classes/external/export_items.php classes/external/get_export_preview.php classes/external/get_export_status.php ``` Export workflow: ```text 1. User requests export preview. 2. Service checks export capability and context. 3. Export preview identifies included media, versions, files, relations, collections, advisories, reviews, and external work metadata. 4. Policy removes unauthorized restricted content. 5. User confirms export. 6. Export package is generated. 7. manifest.json is created. 8. Files are stored through Moodle File API. 9. Export event is triggered. ``` Manifest includes: ```text plugin component archive id export id export timestamp export actor export reason archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Export rule: ```text Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` --- ## 26. Media deletion workflow Deletion is policy-controlled. Deletion states: ```text deleted_soft archived retained purged ``` Deletion workflow: ```text 1. User requests delete media. 2. Service checks mod/uckkarchive:deletemedia. 3. Media policy checks retention, provenance, evidence, collection, and export constraints. 4. Media is soft-deleted when preservation is required. 5. Files are retained or purged according to retention policy. 6. Relations, collections, advisories, and reviews are preserved or anonymized according to policy. 7. Event media_updated or deletion audit event is recorded. ``` Deletion rule: ```text Validated, exported, culturally restricted, integrity-linked, or evidence-linked media must not be silently purged. ``` --- ## 27. Privacy workflow Media privacy is handled by: ```text classes/privacy/provider.php ``` Privacy provider covers: ```text media objects media versions media files media collections media relations media tags content tags when user-created content markers content reviews external works when user-created or user-linked media sources proofs provenance revisions exports ``` Privacy workflow: ```text 1. Privacy API asks for user-linked data. 2. Provider locates media records and related data. 3. Provider exports personal data belonging to the user. 4. Provider redacts third-party or restricted data. 5. Provider deletes, anonymizes, or preserves records according to retention rules. ``` Privacy rule: ```text Privacy export is not a permission bypass. Restricted third-party information and culturally restricted details must be filtered or redacted. ``` --- ## 28. Backup and restore workflow Backup/restore includes: ```text media records media versions media files media relations media tags media collections media collection membership media source records external work records content tags content tag sets content markers content reviews provenance export manifest metadata ``` Restore workflow: ```text 1. Restore recreates archive instance. 2. Restore maps users, courses, contexts, archive ids, media ids, and UUID references. 3. Media objects are restored. 4. Media versions are restored. 5. Files are restored to canonical File API areas. 6. Collections and relations are restored. 7. Content markers and reviews are restored. 8. External work references are restored. 9. Visibility and restricted states remain preserved. ``` Restore rule: ```text Restore must not make restricted, culturally sensitive, or integrity-linked media public. ``` --- ## 29. Event workflow Media events: ```text media_created media_updated media_version_created media_collection_created media_exported content_marker_created content_marker_reviewed external_work_created ``` Event workflow: ```text 1. State-changing service completes successfully. 2. Event is triggered with context and object identifiers. 3. Event does not expose restricted content. 4. Observers may update search, reports, or audit views. ``` Event rule: ```text Events audit successful state changes. Events do not expose restricted content, raw content, private cultural protocol notes, or redacted details. ``` --- ## 30. UI workflow Media UI consists of: ```text media library view media card media upload form media version list media collection view media relation list content advisory panel external work card provenance panel ``` AMD modules: ```text amd/src/media.js amd/src/media_collection.js amd/src/content_advisory.js amd/src/external_work.js ``` UI workflow: ```text 1. Server renders initial permission-filtered data. 2. AMD enhances browsing, filtering, editing, upload, advisory panels, and collection interactions. 3. AJAX services return permission-filtered updates. 4. UI displays warnings, restrictions, and advisory labels. 5. UI never exposes hidden or restricted records by client-side filtering alone. ``` UI rule: ```text Server-side policy is authoritative. Client-side UI is never the security boundary. ``` --- ## 31. Course and archive item linking workflow Media can be linked to: ```text course context archive item proof record Kristal collection external work content marker ``` Link workflow: ```text 1. User selects media to attach or relate. 2. Relation type is selected. 3. Service checks authority on both source and target. 4. Relation is stored. 5. Both media and archive item views can display the relationship according to policy. ``` Canonical relation: ```text belongs_to_item ``` Rule: ```text Linking media to an archive item does not duplicate the media file. ``` --- ## 32. Restricted media workflow Restricted media includes: ```text restricted_integrity restricted_cultural staff_only private ``` Restricted workflow: ```text 1. Media or content marker receives restricted status or suitability. 2. Policy checks restrict view, thumbnail, preview, download, export, and search visibility. 3. UI displays restricted markers only to authorized users. 4. Export excludes or redacts restricted material unless user has authority. ``` Required capabilities: ```text mod/uckkarchive:viewrestrictedmedia mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:viewrestricted ``` Restricted rule: ```text Restricted media must not leak through thumbnails, previews, search facets, export manifests, backup previews, or advisory summaries. ``` --- ## 33. Final media workflow rule ```text Media is managed as a first-class object. Media files live in Moodle File API. Media identity, versions, collections, relations, source records, content advisories, cultural protocol markers, reviews, and export identity live in mod_uckkarchive tables. Media workflow is controlled by server-side policy. Content advisories describe responsible access. Cultural protocol rules protect sensitive knowledge. External works can be referenced without being owned. This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ``` ================================================================================================ FILE: mod/uckkarchive/docs/10_provenance_versioning_validation.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 0414b0b3970c6df3c64f6d71e342d7e9772e7bbec855dd118761c9d0586cc2c6 CONTENT_BYTES: 30016 ================================================================================================ # 10 — Provenance, Versioning and Validation **Path:** `docs/10_provenance_versioning_validation.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Provenance, archive revisions, media versions, content advisory reviews, validation states, contestability, trust rules, and auditability for the self-contained UCKK Archive module. --- ## 1. Purpose This document defines how `mod_uckkarchive` records, verifies, revises, validates, contests, invalidates, preserves, and exports archive/media memory. The module is a self-contained Moodle activity module for: ```text archive memory media library management content advisory governance cultural sensitivity tagging external/foreign media references exportable archive/media packages ``` This document applies to: ```text archive items proof records Kristals media objects media versions media collections media relations media tags content advisory tags content tag sets content markers content reviews external works foreign media references media source records provenance records revision records validation state restricted records export packages export manifests ``` --- ## 2. Core rule Canonical architecture formula: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` Provenance, versioning, validation, and review are internal authority functions of `mod_uckkarchive`. The module uses Moodle for: ```text context users roles capabilities File API Privacy API Backup API Restore API events external services scheduled tasks ``` The module owns its own: ```text archive provenance media provenance media versions archive revisions content advisory reviews cultural protocol review records validation state contestability metadata export manifests ``` --- ## 3. Canonical ownership `mod_uckkarchive` owns: ```text archive records archive items media records media versions media files media collections media collection membership media relations media tags proof records Kristals provenance records revision history validation state restricted archive metadata restricted media metadata content advisory tags cultural sensitivity tags content tag sets content markers content reviews external works foreign media references media source records audience suitability rules export packages export manifests ``` `mod_uckkarchive` does not own: ```text grades transcripts course enrolment authority administrative registry records challenge workflow state Assembly decision authority integrity case authority institutional reporting authority ``` Preserved evidence does not transfer authority. Referenced external works do not become UCKK-owned works. --- ## 4. Required tables Archive tables involved in provenance, versioning, and validation: ```text uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export ``` Media tables involved in provenance and versioning: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` Content advisory and external-work tables involved in review and suitability: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Identifier rule: ```text id = local Moodle database primary key uuid = stable portable object identity ``` UUID rule: ```text Archive objects, media objects, content markers, external works, and export packages use UUIDs for export, restore, duplication, and cross-site portability. ``` --- ## 5. Provenance model Provenance explains where a record, media object, marker, review, or exported package came from. Canonical provenance values: ```text human ai_assisted imported system archive assembly challenge integrity media external_work content_review ``` Provenance rule: ```text Provenance explains origin. Provenance does not grant authority by itself. ``` A record with valid provenance is not automatically validated. A record with AI-assisted provenance is not automatically rejected. A record imported from another system is not automatically trusted. Human review and validation rules decide trust state. --- ## 6. Provenance records `uckkarchive_prov` stores structured provenance for archive-owned records. It must support provenance for: ```text archive items proofs Kristals media objects media versions content markers content reviews external works export packages ``` A provenance record should support: ```text uuid context id course id course module id archive id target table target id target uuid source type source component source identifier source title source URL or reference source description actor user id created time modified time import time AI-assistance flag human review flag file hash manifest reference notes metadata JSON ``` Sensitive provenance notes must be permission-filtered. Provenance records must not expose private cultural protocol details to users who do not have authority to view them. --- ## 7. Archive item lifecycle Canonical archive item statuses: ```text draft submitted under_review validated published restricted contested invalidated superseded archived ``` Status meaning: | Status | Meaning | |---|---| | `draft` | Editable record not submitted for review. | | `submitted` | Submitted for review or validation. | | `under_review` | Currently being reviewed by an authorized human reviewer. | | `validated` | Human reviewer has validated the record. | | `published` | Record is visible according to its visibility policy. | | `restricted` | Record exists but has restricted access. | | `contested` | Record is challenged, disputed, or awaiting clarification. | | `invalidated` | Record is preserved but marked invalid or no longer reliable. | | `superseded` | Record has been replaced by a newer record or revision. | | `archived` | Record is retained for memory, audit, or preservation. | Status rule: ```text Archive status controls workflow state. Visibility controls who can see it. Validation state controls trust. Policy controls actions. ``` --- ## 8. Media lifecycle Canonical media states: ```text draft submitted active restricted superseded archived deleted_soft ``` Status meaning: | Status | Meaning | |---|---| | `draft` | Media metadata or file is being prepared. | | `submitted` | Media is submitted for review, tagging, or validation. | | `active` | Media is available according to policy and visibility. | | `restricted` | Media exists but access is restricted. | | `superseded` | Media has been replaced by a newer version or object. | | `archived` | Media is retained for preservation or audit. | | `deleted_soft` | Media is hidden from normal use but retained according to retention rules. | Media lifecycle rule: ```text File existence is not media availability. Media status controls usability. Visibility controls access. Policy controls download and export. Content advisories describe suitability, cultural protocol, and access conditions. Retention controls deletion. ``` --- ## 9. Validation states Canonical validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Validation meaning: | State | Meaning | |---|---| | `unverified` | No human validation has occurred. | | `human_reviewed` | A reviewer has examined the record but has not fully verified it. | | `verified` | A reviewer has validated the record as reliable for its stated use. | | `contested` | The record is disputed or under challenge. | | `invalidated` | The record is preserved but marked unreliable or incorrect. | | `archived` | The record is preserved for memory, history, or audit. | Validation rules: ```text Validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. ``` AI may assist with: ```text suggesting tags suggesting summaries suggesting locator candidates suggesting duplicate detection suggesting metadata normalization suggesting provenance classification ``` AI output must remain: ```text ai_assisted unverified human-review required ``` until reviewed by an authorized human. --- ## 10. Revision model for archive items Archive item revision uses: ```text uckkarchive_rev ``` Archive revision permission: ```text mod/uckkarchive:reviseitem ``` Removed capability: ```text mod/uckkarchive:versionitem = not used ``` An archive revision must be created when a meaningful change occurs to: ```text title description public summary visibility validation state status provenance restricted metadata source reference linked proof linked Kristal linked media content advisory relationship export-relevant metadata ``` An archive revision should record: ```text uuid archive item id archive item uuid revision number previous revision id actor user id change reason change summary changed fields old values where safe new values where safe created time validation state before change validation state after change status before change status after change visibility before change visibility after change metadata JSON ``` Restricted old/new values must be redacted when viewed by users without authority. --- ## 11. Media versioning model Media versioning uses: ```text uckkarchive_media_version ``` Media version permission: ```text mod/uckkarchive:versionmedia ``` A media version must be created when there is a meaningful change to: ```text original file replacement file preview file derivative file thumbnail caption transcript technical metadata file hash source classification license/rights metadata access restriction cultural protocol restriction content advisory state ``` A media version should record: ```text uuid media id media uuid version number previous version id actor user id change reason change summary file area file item id filename mime type file size content hash source type rights metadata created time metadata JSON ``` Media versioning rule: ```text Media files are not silently overwritten. Meaningful replacement creates a new media version. Derived files remain linked to their source version. ``` --- ## 12. Media source records Media source classification uses: ```text uckkarchive_media_source ``` Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Media source records must clarify: ```text whether UCKK produced the media whether the media was submitted to UCKK whether the media was imported whether the media is only referenced whether UCKK may store a copy whether UCKK may export a copy whether UCKK may show previews whether teaching use requires context whether access is culturally restricted ``` External/foreign media rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` --- ## 13. External work records External works use: ```text uckkarchive_external_work ``` External work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External work records should support: ```text uuid title creator publisher publication year work type language edition ISBN or identifier URL or catalog reference rights status source ownership description citation text metadata JSON created time modified time ``` External work records may be linked to: ```text archive items media objects content markers content reviews media source records export manifests ``` External work records may store references and advisory metadata without storing the full external work. --- ## 14. Content advisory model The content advisory subsystem covers: ```text content advisories content warnings cultural advisories cultural protocols audience suitability content markers tag sets reviews external works foreign media references ``` Canonical content advisory tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review ``` Architecture rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` Content advisories may apply to: ```text archive item media object media version media collection external work specific timecode specific page specific chapter specific paragraph specific scene manual reference ``` --- ## 15. Content tags `uckkarchive_content_tag` defines reusable advisory and cultural protocol tags. Content advisory tag examples: ```text sexual_violence violence racism colonial_violence death self_harm substance_use nudity explicit_language culturally_sensitive sacred_content ceremonial_content restricted_knowledge grief_or_mourning requires_context not_for_children ``` Cultural protocol tag examples: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Content tag fields should support: ```text id uuid tag key display name description tag type severity default audience default cultural protocol flag restricted flag active flag sort order created time modified time ``` --- ## 16. Content tag sets `uckkarchive_content_tag_set` groups advisory tags into reusable vocabularies. Examples: ```text general_advisories cultural_protocols classroom_suitability integrity_sensitive youth_access ``` A tag set should support: ```text uuid key display name description scope active flag created time modified time metadata JSON ``` Content tag set rule: ```text Content tag sets organize vocabularies. They do not replace policy. They do not override cultural protocol review. ``` --- ## 17. Content markers and locators `uckkarchive_content_marker` links a content advisory or cultural protocol tag to a precise location inside an internal media object, archive item, media version, or external work. Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Content marker examples: ```text Movie Maïna -> sexual_violence -> 01:12:30-01:15:10 Book The Body Keeps the Score -> sexual_violence -> page 42-45 PDF -> culturally_sensitive -> page 7 Audio -> grief_or_mourning -> 00:08:12-00:09:40 Website -> colonial_violence -> url_fragment #section-3 ``` A content marker should support: ```text uuid context id archive id target type target id target uuid external work id external work uuid media id media uuid media version id media version uuid tag id tag uuid tag set id tag set uuid locator type locator start locator end locator label severity audience suitability review state restricted flag cultural protocol flag created by reviewed by created time reviewed time notes redacted notes metadata JSON ``` Content marker rule: ```text A content marker can point to internal media, archive items, media versions, external works, or manual references. A content marker must include enough locator information to be useful without storing unauthorized copies of external content. ``` --- ## 18. Content reviews `uckkarchive_content_review` records human review of content markers, advisory tags, cultural protocol notes, suitability, and restriction decisions. Content advisory review states: ```text draft pending_review reviewed approved contested retired ``` Content review should support: ```text uuid content marker id content marker uuid reviewer user id review type review state review decision audience suitability severity cultural protocol decision restriction decision redaction decision export decision teaching context note private reviewer note created time modified time reviewed time metadata JSON ``` Content review rule: ```text AI may suggest tags or markers, but human review is required before advisory status becomes approved. ``` Cultural review rule: ```text Cultural protocol decisions require authorized human review. AI cannot approve cultural access. AI cannot remove cultural restrictions. AI cannot downgrade cultural sensitivity. ``` --- ## 19. Audience suitability Canonical audience suitability values: ```text general guided mature restricted restricted_cultural restricted_integrity staff_only ``` Suitability rule: ```text Audience suitability is advisory and policy-relevant. It does not automatically grant access. It informs warnings, teaching context, filtering, exports, and restrictions. ``` --- ## 20. Content advisory severity Canonical severity values: ```text notice moderate strong restricted ``` Severity rule: ```text Severity guides presentation and review priority. Restricted severity requires policy evaluation before access or export. ``` --- ## 21. Visibility and restrictions Canonical visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Compatibility rule: ```text institutional must normalize to institution. ``` Visibility rule: ```text Visibility defines the intended audience. Restrictions define access constraints. Policy decides whether the current user can act. ``` Content advisory restrictions may affect: ```text viewing download preview export thumbnail display public summary display classroom use youth access external sharing manifest disclosure ``` --- ## 22. Contestability Archive items, media metadata, content markers, and content reviews must be contestable when policy allows. Contestable targets include: ```text archive item validation archive item status media source classification media version metadata content tag assignment content marker locator audience suitability cultural protocol classification external work citation provenance statement export redaction decision ``` Contestation should record: ```text target type target id target uuid contesting user id reason evidence status reviewer decision created time resolved time metadata JSON ``` Contested records remain preserved. Contested records must display safe warning state to authorized viewers. --- ## 23. Invalidation Invalidation marks a record as unreliable, incorrect, or unsuitable for its previous use. Invalidation does not automatically delete the record. Invalidation applies to: ```text archive item proof Kristal media metadata media version metadata content marker content review external work reference provenance record ``` Invalidation must record: ```text actor reason time target previous state new state related revision related provenance notes ``` Invalidation rule: ```text Invalidated records are preserved unless retention policy requires deletion. Invalidated records must not be silently used as verified records. ``` --- ## 24. Export trust model Export packages must include enough provenance, validation, revision, media version, content advisory, and external work metadata to make the package explainable. Canonical manifest filename: ```text manifest.json ``` Manifest includes: ```text plugin component archive id export id export timestamp export actor export reason archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Export rule: ```text Exports are portable and explainable. Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` --- ## 25. Hashing and file integrity Media versions and export packages must preserve file integrity metadata. File integrity metadata should include: ```text filename mime type file size content hash file area item id media uuid media version uuid created time source classification ``` Hashing rule: ```text Hashes support integrity and audit. Hashes do not grant access. Hashes do not replace provenance. ``` --- ## 26. Policy classes Archive policy belongs in: ```text classes/local/archive_policy.php ``` Media policy belongs in: ```text classes/local/media_policy.php ``` Content advisory policy belongs in: ```text classes/local/content_policy.php ``` Policy classes enforce: ```text context access capability gates ownership visibility media status archive item status validation state restricted state download authority export authority content advisory rules cultural protocol rules privacy policy retention policy redaction policy workflow rules ``` No controller, AMD module, template, output class, or form may replace policy classes. --- ## 27. Capabilities Archive capabilities involved in provenance, revision, validation, and export: ```text mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Media capabilities involved in provenance and media versioning: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Capability rule: ```text Capabilities are gates, not full authority. Policy classes still enforce context, ownership, visibility, status, validation state, restricted state, content advisory rules, cultural protocol rules, retention, and redaction. ``` --- ## 28. Events Events must audit successful state changes. Relevant event classes include: ```text classes/event/archive_item_created.php classes/event/archive_item_validated.php classes/event/archive_item_revised.php classes/event/archive_item_exported.php classes/event/media_created.php classes/event/media_updated.php classes/event/media_version_created.php classes/event/media_exported.php classes/event/content_marker_created.php classes/event/content_marker_reviewed.php classes/event/external_work_created.php ``` Events must include safe identifiers: ```text context id object id object uuid when appropriate related user id when safe action type created time ``` Events must not expose: ```text restricted content raw media content private reviewer notes private cultural protocol notes redacted metadata unauthorized external work details ``` --- ## 29. External services External service files related to provenance, versioning, and validation include: ```text classes/external/update_provenance.php classes/external/validate_item.php classes/external/revise_item.php classes/external/add_media_version.php classes/external/get_media_versions.php classes/external/get_content_tags.php classes/external/get_content_tag_sets.php classes/external/get_content_markers.php classes/external/add_content_marker.php classes/external/update_content_marker.php classes/external/delete_content_marker.php classes/external/review_content_marker.php classes/external/get_external_works.php classes/external/get_external_work.php classes/external/add_external_work.php classes/external/update_external_work.php ``` Service rule: ```text External services must check context, capability, visibility, status, review state, cultural protocol restrictions, redaction rules, and policy class decisions. ``` Services must never trust client-provided validation, review, or restriction state without server-side policy evaluation. --- ## 30. Privacy and redaction Provenance, revisions, validation records, media versions, content markers, and content reviews may contain personal or sensitive information. Privacy coverage must include: ```text archive item authorship media submitter metadata reviewer metadata validator metadata revision actors content marker creators content reviewers external work notes restricted notes private review notes cultural protocol notes export manifests ``` Redaction must apply to: ```text private notes restricted metadata cultural protocol details integrity-related details sensitive content advisory notes external work notes that cannot be shared old revision values not visible to the current user ``` Privacy rule: ```text A user may receive their own personal data through Moodle Privacy API. A user must not receive restricted cultural, integrity, or third-party information merely because it is stored near their record. ``` --- ## 31. Backup and restore Backup must preserve: ```text provenance records archive revisions media versions content tags content tag sets content markers content reviews external works media source records validation state contestability metadata export manifests when included ``` Restore must remap: ```text context ids course ids course module ids archive ids archive item ids media ids media version ids content marker ids external work ids user ids where possible file item ids ``` Restore rule: ```text Restore reconstructs archive-owned memory. Restore does not create grades, challenge workflow authority, Assembly decision authority, integrity case authority, or institutional reporting authority. ``` --- ## 32. Import behavior Imported records must preserve source provenance. Imported records begin as: ```text unverified ``` unless a trusted human validation record is imported and accepted under policy. Imported media must include source classification. Imported content markers must include review state. Imported external works must not imply UCKK ownership. Import rule: ```text Import can preserve prior claims. Import does not automatically validate prior claims. ``` --- ## 33. External/foreign media examples The module must support advisory metadata for external or foreign works without requiring UCKK to store the full work. Examples: ```text Movie Maïna -> sexual_violence -> 01:12:30-01:15:10 Book The Body Keeps the Score -> sexual_violence -> page 42-45 PDF -> culturally_sensitive -> page 7 Audio -> grief_or_mourning -> 00:08:12-00:09:40 Website -> colonial_violence -> url_fragment #section-3 ``` External reference rule: ```text The archive may store locator, advisory, review, citation, and teaching-context metadata for an external work. The archive must not store or export unauthorized copies of external works. ``` --- ## 34. Required local classes Required local authority classes include: ```text classes/local/archive_policy.php classes/local/content_marker.php classes/local/content_policy.php classes/local/content_review.php classes/local/content_tag.php classes/local/content_tag_set.php classes/local/external_work.php classes/local/media_policy.php classes/local/media_source.php classes/local/media_version.php classes/local/provenance.php classes/local/revision.php classes/local/uuid.php ``` Implementation rule: ```text Business rules belong in classes/local. Controllers coordinate. Services validate API contracts and call policy/domain classes. Templates render pre-filtered data. AMD modules never authorize access. ``` --- ## 35. Tests Testing must cover: ```text provenance creation archive revision creation media version creation validation transitions contestation transitions invalidation behavior content tag creation content tag set behavior content marker locator behavior content review workflow external work references media source classification restricted visibility cultural protocol restriction export manifest provenance privacy redaction backup/restore remapping service permission checks ``` Required tests include: ```text tests/archive_test.php tests/content_advisory_test.php tests/external_work_test.php tests/media_library_test.php tests/privacy_provider_test.php tests/services_test.php tests/backup_restore_test.php ``` Testing rule: ```text Tests verify final target behavior. Tests must not depend on historical gap documents. Tests must not require mod/uckkarchive:versionitem. ``` --- ## 36. Non-negotiable rules ```text Validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. Media files are not silently overwritten. Meaningful media replacement creates a media version. Meaningful archive item change creates an archive revision. Content advisories are first-class records, not only JSON metadata. External works can be referenced without being copied. External work reference does not imply UCKK ownership. Provenance explains origin but does not grant authority. Exports must remain portable, explainable, permission-filtered, and redaction-aware. ``` --- ## 37. Final rule ```text This document defines the final target behavior for provenance, versioning, validation, content advisory review, external work references, and trust governance. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ``` ================================================================================================ FILE: mod/uckkarchive/docs/11_privacy_retention_redaction.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 1f8d5a33745e40624a0392efc22105cc7b8b013593798e5c68b3052ff8e1d963 CONTENT_BYTES: 31290 ================================================================================================ # 11 — Privacy, Retention, and Redaction **Path:** `docs/11_privacy_retention_redaction.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Privacy, retention, deletion, anonymization, redaction, restricted access, content advisory privacy, cultural protocol privacy, external work references, File API data, and Moodle Privacy API responsibilities. --- ## 1. Purpose This document defines the privacy, retention, and redaction architecture for `mod_uckkarchive`. `mod_uckkarchive` is a self-contained Moodle activity module for: ```text archive memory media library management content advisory governance cultural protocol handling external work references provenance validation revision history export packages ``` The module stores records that may contain personal data, educational data, evidence, cultural sensitivity metadata, restricted content, advisory notes, and external media references. The module must preserve archive memory while still respecting privacy, retention, redaction, and deletion rules. --- ## 2. Core privacy decision Canonical formula: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` Privacy behavior follows the same architecture. `mod_uckkarchive` uses Moodle for: ```text Privacy API context ownership user identity capabilities course module access role-based access File API storage backup and restore boundaries external service restrictions events scheduled tasks ``` `mod_uckkarchive` owns privacy behavior for the records it stores internally. --- ## 3. Privacy ownership boundary `mod_uckkarchive` owns privacy handling for: ```text archive records archive items media records media versions media files media collections media relations media tags proof records Kristals provenance records revision records validation state restricted archive metadata restricted media metadata content advisory tags cultural sensitivity tags content tag sets content markers content reviews external work references media source records audience suitability rules export packages export manifests ``` `mod_uckkarchive` does not own privacy behavior for records controlled by: ```text Moodle gradebook local_uckk mod_uckkchallenge mod_uckkassembly tool_uckkintegrity report_uckk ``` The archive may preserve snapshots or references from those systems. Preservation does not transfer system authority. Privacy export, redaction, deletion, or anonymization applies only to archive-owned records unless external data has been copied into archive-owned tables or files. --- ## 4. Moodle Privacy API contract The plugin privacy provider is: ```text classes/privacy/provider.php ``` The provider must declare metadata for all user-related data stored by `mod_uckkarchive`. The provider must support Moodle privacy operations for: ```text metadata declaration contexts containing user data export of user data deletion of user data for a context deletion of user data for a user in a context deletion of all user data in a context ``` The privacy provider must cover: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` The privacy provider must also cover File API data stored in all plugin file areas. --- ## 5. Data categories The module may store these privacy-relevant data categories: ```text user identity references creator identity modifier identity reviewer identity validator identity export actor identity archive contributor identity media submitter identity proof submitter identity content reviewer identity provenance actor identity timestamps comments notes validation statements review statements content advisory statements cultural protocol notes file metadata file contents external work metadata source ownership metadata audience suitability metadata restricted access metadata redaction metadata retention metadata export metadata ``` The module must treat the following as sensitive: ```text restricted archive records restricted media records restricted cultural protocol notes integrity-sensitive records proof records personal testimony personal educational work personal portfolio material validation comments content review notes content advisories involving trauma or violence markers for sexual violence, self-harm, grief, racism, colonial violence, or cultural sensitivity external work references tied to sensitive teaching or review context ``` --- ## 6. Personal data fields Any table with user references must be considered privacy-relevant. Common user reference fields include: ```text userid createdby modifiedby submittedby validatedby reviewedby exportedby deletedby actorid sourceuserid ownerid ``` Common timestamp fields include: ```text timecreated timemodified timesubmitted timevalidated timereviewed timeexported timedeleted ``` Common privacy-relevant text fields include: ```text title name description summary body content notes reviewnotes validationnotes provenancenotes redactionnotes culturalnotes advisorynotes teachingnotes sourcecitation externalreference ``` All privacy provider logic must inspect both direct user fields and indirect user references embedded in structured metadata. --- ## 7. Archive privacy Archive items may contain: ```text personal submissions course work portfolio records proof records challenge evidence assembly-related preserved material integrity-related preserved material public summaries restricted notes provenance history validation history revision history export history ``` Archive privacy rule: ```text Archive records must remain understandable over time without exposing more personal data than the requesting user is allowed to see. ``` Archive privacy export must include only records the requesting user has rights to receive through Moodle Privacy API rules and archive policy. Archive deletion must respect retention rules, preservation duties, legal or cultural restrictions, and course context deletion. --- ## 8. Media privacy Media objects may contain: ```text uploaded files original files preview files thumbnails derivatives captions transcripts attachments metadata source information rights information contributors media versions relations collections tags content advisories content markers ``` Media privacy rule: ```text Media file existence is not access permission. Access is resolved by context, capability, visibility, media status, content advisory rules, cultural protocol rules, and retention state. ``` Media privacy export must include media metadata and files only when the user has the right to receive them. For privacy export, derivative files must not expose restricted source material if the user cannot access the original or relevant restricted metadata. --- ## 9. Content advisory privacy Content advisories may reveal sensitive information about a work, a class, a learner, a community, a cultural protocol, or an institutional review. The content advisory subsystem includes: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review ``` Content advisory data may include: ```text advisory tag keys cultural sensitivity tags cultural protocol tags locator references timecode ranges page ranges chapter ranges scene references review notes suitability decisions restriction decisions review actor identity review timestamps contestation notes ``` Content advisory privacy rule: ```text Content advisories are metadata, but they can still be sensitive. They must be permission-filtered before display, export, search, backup preview, or API return. ``` Public users may see a simplified advisory label when appropriate. Restricted users may see detailed markers, review notes, and cultural protocol notes only when policy allows. --- ## 10. Cultural protocol privacy Cultural protocol data may be more sensitive than ordinary content advisory data. Cultural protocol tags include: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Cultural protocol privacy rule: ```text Cultural protocol data must be treated as restricted by default when marked restricted_cultural or when a policy rule requires review. ``` The module must support: ```text restricted cultural visibility staff-only notes review-only notes public-safe advisory summaries export exclusion metadata-only export redacted export contextual teaching notes ``` AI may suggest advisory or cultural tags. AI must not approve cultural access, resolve contestations, or authorize restricted cultural viewing. --- ## 11. External work privacy External works are represented by: ```text uckkarchive_external_work ``` External works may include: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External work references may store: ```text title creator publisher year edition URL citation identifier source notes teaching notes advisory markers cultural protocol notes rights notes ``` External work privacy rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, locators, teaching notes, and cultural protocol notes. The archive must not imply ownership over third-party works. ``` External work metadata may be public, but local notes, teaching notes, review notes, cultural notes, and advisory decisions may be restricted. --- ## 12. Media source privacy Media source records are represented by: ```text uckkarchive_media_source ``` Media source values include: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values include: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Media source privacy rule: ```text Source describes origin and rights context. Source does not grant access by itself. Source does not override content advisory, cultural protocol, visibility, or retention policy. ``` Media source records may include personal data when the source is a user, partner, member, submitter, reviewer, or rights contact. --- ## 13. Visibility and restricted data Canonical visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Compatibility rule: ```text institutional must normalize to institution. ``` Visibility rule: ```text Visibility controls who may see the record. Capability controls whether the user may attempt the action. Policy resolves final access. ``` Restricted data must never be returned by: ```text templates output classes external services AMD calls pluginfile URLs exports search results event payloads debug output logs backup previews ``` unless the active policy explicitly allows it. --- ## 14. Redaction model The module must support multiple redaction levels. Canonical redaction levels: ```text none minimal standard strict metadata_only fully_hidden ``` Redaction level meanings: | Redaction level | Meaning | |---|---| | `none` | No redaction required for the current viewer/action. | | `minimal` | Hide private notes and internal review details. | | `standard` | Hide sensitive metadata, restricted notes, and personal identifiers not required for the action. | | `strict` | Hide detailed content, locators, notes, actor identity, and restricted metadata. | | `metadata_only` | Show only safe title/type/status-level metadata. | | `fully_hidden` | Do not reveal that the record exists, unless policy requires a generic restricted notice. | Redaction rule: ```text Redaction happens before rendering, before service return, before export packaging, and before search indexing. ``` --- ## 15. Redaction targets Redaction may apply to: ```text names user identifiers emails profile links free-text notes validation notes review notes cultural protocol notes content advisory notes precise locators timecodes page ranges external work notes source ownership notes restricted tags file names file contents thumbnails previews transcripts captions derivatives provenance details revision details export details ``` Redaction must preserve enough safe metadata to keep archive records understandable when policy permits metadata display. --- ## 16. Content advisory redaction Content advisory redaction must support both safety and non-disclosure. Example display modes: ```text no_advisory_visible summary_only general_warning tag_names_only tags_with_locator tags_with_review_summary full_review_detail ``` Example public-safe display: ```text Content advisory: mature themes. ``` Example guided-access display: ```text Content advisory: sexual violence, page range available to authorized educators. ``` Example restricted display: ```text Content advisory: sexual_violence, page 42-45, reviewed by authorized staff, approved for guided mature audience only. ``` Content advisory redaction rule: ```text Precise locators and review notes are restricted unless the viewer has policy permission to see them. ``` --- ## 17. Cultural protocol redaction Cultural protocol redaction must avoid revealing restricted cultural knowledge through metadata. For restricted cultural content, even the title, source, tag, marker, or locator may require redaction. Cultural redaction modes: ```text public_safe_notice restricted_notice metadata_only protocol_summary reviewer_only_detail fully_hidden ``` Cultural protocol redaction rule: ```text If revealing the advisory would reveal restricted knowledge, the advisory itself must be redacted. ``` Public-safe examples: ```text This item has access conditions. This item requires contextual guidance. This item is not available for public export. ``` Avoid public exposure of: ```text restricted ceremonial details sacred content descriptions community-specific restricted terms elder review notes non-public protocol rules precise locators for restricted knowledge ``` --- ## 18. File privacy All files must be stored through Moodle File API. Canonical archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Canonical content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File privacy rule: ```text No plugin file may be served unless pluginfile policy confirms context, file area, item id, capability, visibility, media status, advisory policy, cultural protocol policy, retention state, and redaction rules. ``` Forbidden storage: ```text No production archive/media files in unmanaged public folders. No binary media files directly in custom database fields. No direct public file URLs as authority. ``` --- ## 19. Pluginfile privacy `mod_uckkarchive_pluginfile()` in `lib.php` must route file access through a central policy layer. The pluginfile handler must check: ```text context validity course module access user login requirements capability file area registry item ownership media ownership media version visibility restricted state content advisory policy cultural protocol policy retention state soft deletion state redaction state ``` The pluginfile handler must not expose files based only on: ```text context id file area item id filename stored_file existence ``` --- ## 20. Retention model Retention defines how long archive-owned records and files remain available. Canonical retention outcomes: ```text retain retain_restricted retain_metadata_only redact anonymize soft_delete delete_files_keep_record delete_record_keep_audit delete_all_allowed_data ``` Retention is decided by: ```text course context archive policy media policy content policy validation state restricted state cultural protocol state integrity-related state export state legal or institutional preservation requirement user deletion request course deletion request ``` Retention rule: ```text The archive is a memory system. Deletion is not always the correct outcome. When preservation is required, use restriction, redaction, anonymization, or metadata-only retention. ``` --- ## 21. Soft deletion Canonical soft-deleted state: ```text deleted_soft ``` Soft deletion means: ```text not visible in ordinary UI not searchable by ordinary users not exportable by ordinary users not downloadable by ordinary users retained for policy, audit, restore, or retention purposes available only to authorized roles when policy allows ``` Soft deletion must record: ```text deleted flag deletedby timedeleted delete reason retention outcome redaction level ``` Soft-deleted files must not be served through pluginfile unless policy explicitly allows administrative recovery. --- ## 22. Anonymization Anonymization replaces identifying user data while preserving archive meaning where allowed. Anonymization may apply to: ```text createdby modifiedby submittedby validatedby reviewedby exportedby notes comments source identity file metadata provenance actor fields review actor fields ``` Anonymization rule: ```text Anonymized archive records must not retain direct identifiers for the anonymized user unless retention policy explicitly requires them. ``` Anonymized values must not create fake user identities. Use neutral values such as: ```text anonymized_user removed_user redacted_actor ``` --- ## 23. Deletion Deletion must be deliberate and policy-driven. Deletion may involve: ```text database record deletion file deletion metadata deletion user reference anonymization export package deletion search index purge cache purge event/log non-expansion soft deletion instead of hard deletion ``` Deletion rule: ```text Hard deletion is allowed only when retention, audit, cultural protocol, integrity, and legal preservation rules permit it. ``` For user deletion requests, the privacy provider must choose the correct outcome for each record: ```text delete soft_delete anonymize redact retain_restricted retain_metadata_only ``` --- ## 24. Export privacy Archive/media exports are generated by `mod_uckkarchive`. Institutional reporting exports are owned by `report_uckk`. Archive export packages may contain: ```text archive items media metadata media files media versions proofs Kristals provenance revision history validation state content advisories content markers content reviews external work references export manifests ``` Export privacy rule: ```text Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` Every export package must include: ```text manifest.json ``` The manifest must include redaction and restriction metadata when applicable. The manifest must not expose restricted notes to unauthorized export recipients. --- ## 25. Export redaction Export redaction must support: ```text full export restricted export redacted export metadata-only export public export teaching export review export integrity export cultural protocol restricted export ``` Export redaction must filter: ```text files file names media versions content markers precise locators review notes cultural notes private provenance revision comments actor identity restricted metadata external work teaching notes ``` Export packages must not include hidden file areas unless policy allows. --- ## 26. Privacy export for a user When Moodle requests a user data export, `classes/privacy/provider.php` must include user-related records from: ```text archive items created by the user archive items modified by the user proofs submitted by the user Kristals created or modified by the user media submitted by the user media versions created by the user media collections created by the user media relations created by the user content markers created by the user content reviews performed by the user external work references created by the user provenance records involving the user revision records involving the user export records created by the user files uploaded by the user ``` Privacy export must respect access restrictions and Moodle Privacy API expectations. If a record contains multiple users, export only the requesting user’s appropriate data unless policy allows broader disclosure. --- ## 27. Privacy deletion for a user When Moodle requests deletion of data for a user, the provider must evaluate each record where the user appears. Possible outcomes: ```text delete if private draft and no preservation need soft_delete if user-owned but audit retention is required anonymize if archive meaning must remain redact if sensitive notes include the user retain_restricted if preservation is required retain_metadata_only if only non-identifying record structure must remain ``` User deletion must not: ```text break archive referential integrity erase required validation history without replacement erase required provenance without policy decision expose other users' data delete third-party records owned by other users delete external works because one user referenced them ``` --- ## 28. Course/context deletion When a Moodle context is deleted, the plugin must process archive-owned data in that context. Context deletion may result in: ```text full deletion soft deletion archive retention metadata-only retention restricted institutional retention export package purge file purge ``` Context deletion rule: ```text Context deletion removes ordinary course access. It does not automatically erase preserved archive memory when retention policy requires preservation. ``` If retained after context deletion, the record must no longer appear in ordinary course UI. --- ## 29. Backup and restore privacy Backup must include only archive-owned data intended for backup. Restore must reconstruct archive-owned records only. Backup/restore privacy rule: ```text Backup and restore do not grant new access rights. Restored records must still be governed by context, capabilities, visibility, restricted state, content advisory rules, cultural protocol rules, and redaction policy. ``` Backup must include enough metadata to restore: ```text retention state redaction level restricted state content advisory state cultural protocol state external work references media source records review states ``` Backup must not expose restricted content in backup logs, progress messages, or error messages. --- ## 30. Search and indexing privacy Search and indexing must use redacted data. Search indexes must not include: ```text restricted notes cultural protocol notes private validation comments private review notes restricted advisory details precise restricted locators hidden external work teaching notes restricted file contents restricted transcripts restricted captions ``` Search result rule: ```text Search results must reveal only records and fields the viewer is allowed to see. ``` If a record is hidden by policy, search must not reveal its title, type, location, or existence unless policy allows a generic restricted notice. --- ## 31. Events and audit privacy Events must audit successful state changes. Event payloads must not expose: ```text restricted content raw file content private notes restricted cultural notes redacted metadata personal testimony precise advisory locators sensitive review text ``` Events may include: ```text context id object id related user id where required anonymous status flags safe object type safe action type ``` Event privacy rule: ```text Events are for audit, not content transport. ``` --- ## 32. External service privacy External services must return policy-filtered data only. External service classes must check: ```text context capability visibility ownership media status archive item status validation state restricted state content advisory policy cultural protocol policy redaction level retention state ``` External services must not return raw restricted data and rely on AMD, Mustache, or browser-side filtering. Client-side code is not a privacy boundary. --- ## 33. UI privacy Templates and output classes must receive pre-filtered data. UI privacy rule: ```text Templates render. They do not authorize. They do not redact. They do not decide access. ``` Output classes may format data but must not override policy. AMD modules may request data but must not decide whether data is allowed. --- ## 34. AI-assisted metadata privacy AI may assist with: ```text draft summaries suggested tags suggested content advisories suggested content markers suggested transcripts suggested descriptions suggested metadata normalization ``` AI must not: ```text approve cultural protocol access validate archive records invalidate archive records close contestations override human review decide privacy deletion decide final redaction policy ``` AI-generated suggestions must be marked with provenance: ```text ai_assisted ``` AI-generated content advisories or markers must remain unapproved until human review. --- ## 35. Content review privacy Content reviews are represented by: ```text uckkarchive_content_review ``` Content reviews may contain: ```text reviewer identity review timestamp review decision suitability decision cultural protocol decision restriction decision private notes public-safe summary contestation state ``` Content review privacy rule: ```text Review decisions may be visible. Review notes are restricted unless policy allows. ``` The system must distinguish: ```text public review summary internal review notes restricted cultural notes staff-only notes ``` --- ## 36. Tags and tag sets privacy Content tags and tag sets may be public vocabularies or restricted vocabularies. Tag sets are represented by: ```text uckkarchive_content_tag_set ``` Tag set examples: ```text general_advisories cultural_protocols classroom_suitability integrity_sensitive youth_access ``` Tag privacy rule: ```text A tag key may be public, restricted, or culturally restricted. The presence of a restricted tag on a record may itself be restricted. ``` Do not assume all tags can be shown to all users. --- ## 37. Reports and institutional exports boundary `mod_uckkarchive` owns archive export packages. `report_uckk` owns institutional reporting views and institutional report exports. Privacy boundary rule: ```text mod_uckkarchive does not become report_uckk. report_uckk does not bypass mod_uckkarchive privacy policy when reading archive data. ``` When report systems consume archive data, they must receive redacted or permission-filtered data appropriate to the report context and actor. --- ## 38. Retention configuration The module should support configurable retention settings for: ```text draft archive items submitted archive items validated archive items restricted archive items media originals media derivatives media previews media thumbnails content reviews content markers external work references export packages export manifests soft-deleted records ``` Retention configuration must not allow a lower-privileged user to disable required preservation, audit, privacy, cultural protocol, or integrity rules. --- ## 39. Scheduled retention tasks Scheduled tasks may support: ```text purge expired exports purge expired temporary files redact expired review notes anonymize expired user references remove orphaned derivatives rebuild redacted search indexes verify soft-deleted file inaccessibility ``` Task privacy rule: ```text Scheduled tasks reuse classes/local policy logic. Scheduled tasks do not bypass retention, redaction, cultural protocol, or privacy rules. ``` --- ## 40. Required implementation files Privacy implementation: ```text classes/privacy/provider.php ``` Policy implementation: ```text classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php ``` Retention and redaction helpers may be implemented in: ```text classes/local/retention_policy.php classes/local/redaction_policy.php classes/local/metadata_validator.php classes/local/file_area_registry.php ``` Content advisory implementation: ```text classes/local/content_tag.php classes/local/content_tag_set.php classes/local/content_marker.php classes/local/content_review.php classes/local/external_work.php classes/local/media_source.php ``` Service implementation must respect privacy in: ```text classes/external/* ``` File serving must respect privacy in: ```text lib.php ``` Backup/restore must preserve privacy metadata in: ```text backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` --- ## 41. Required tests Privacy and redaction tests must verify: ```text privacy export includes correct user data privacy deletion respects retention policy restricted records are hidden from unauthorized users pluginfile refuses unauthorized file access media originals are not exposed through derivatives content advisories are redacted by policy cultural protocol notes are hidden by default external work notes are permission-filtered exports do not bypass privacy backup/restore preserves restricted state search does not reveal hidden records events do not expose restricted content AI-assisted suggestions require human review ``` Required test files include: ```text tests/privacy_provider_test.php tests/file_api_test.php tests/export_test.php tests/content_advisory_test.php tests/external_work_test.php tests/media_library_test.php tests/services_test.php ``` --- ## 42. Final privacy rule ```text mod_uckkarchive preserves archive memory without treating preservation as unlimited disclosure. Every archive item, media object, file, content marker, content review, external work reference, export, and manifest is governed by context, capability, visibility, retention, redaction, content advisory policy, cultural protocol policy, and Moodle Privacy API rules. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/12_backup_restore.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 534dcd9ef61100283d9eb8758f72c32e0ee295f0d425f9b780141481a751a221 CONTENT_BYTES: 31306 ================================================================================================ # 12 — Backup and Restore **Path:** `docs/12_backup_restore.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Backup and restore contract for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Purpose This document defines the backup and restore behavior for `mod_uckkarchive`. `mod_uckkarchive` is a Moodle-native activity module with a self-contained internal archive, media library, and content advisory system. Canonical formula: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` Backup and restore must preserve module-owned records, files, metadata, relations, provenance, revision history, validation state, content advisories, cultural protocol metadata, external work references, and export manifests. Backup and restore must not turn `mod_uckkarchive` into the owner of external workflow domains. --- ## 2. Core backup decision `mod_uckkarchive` backup must preserve: ```text activity instance archive records archive items media records media versions media files media collections media collection membership media relations media tags proof records Kristals provenance records revision history validation state restricted archive metadata restricted media metadata content advisory tags content tag sets content markers content reviews external works foreign media references media source records audience suitability rules export package metadata export manifests Moodle File API file areas ``` Restore must reconstruct the same module-owned state in the restored activity context. Restore must not create or claim ownership over external authority records. --- ## 3. Domain boundary rule Canonical ownership map: ```text GRADE_OWNER = Moodle gradebook REGISTRY_OWNER = local_uckk CHALLENGE_OWNER = mod_uckkchallenge ASSEMBLY_OWNER = mod_uckkassembly INTEGRITY_OWNER = tool_uckkintegrity REPORT_OWNER = report_uckk ARCHIVE_OWNER = mod_uckkarchive ``` Backup/restore boundary rules: ```text Restore must not create grades. Restore must not create official transcripts. Restore must not create enrolments. Restore must not create global registry authority. Restore must not create challenge workflow authority. Restore must not create Assembly decision authority. Restore must not create integrity case authority. Restore must not create institutional reporting authority. Restore must not claim copyright ownership over external works. ``` The archive may restore references, preserved snapshots, evidence, media, content advisories, and provenance from external domains. Restoring a reference does not restore external authority. --- ## 4. Required backup and restore files Canonical backup/restore files: ```text backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` File responsibilities: | File | Responsibility | |---|---| | `backup_uckkarchive_activity_task.class.php` | Defines the Moodle backup task, encoded content links, file areas, and backup step registration. | | `backup_uckkarchive_stepslib.php` | Defines the backup structure for module-owned records. | | `restore_uckkarchive_activity_task.class.php` | Defines the Moodle restore task, decode rules, file areas, and restore step registration. | | `restore_uckkarchive_stepslib.php` | Restores module-owned records, maps IDs, restores files, and reconnects relations. | Implementation rule: ```text Backup/restore code must use Moodle backup and restore APIs. It must not use raw filesystem copies. It must not bypass Moodle File API. ``` --- ## 5. Backup root structure The backup XML structure must begin with the activity instance: ```text uckkarchive ``` The activity root contains child structures for: ```text items proofs kristals provenance_records revisions exports media media_versions media_relations media_tags media_collections media_collection_items content_tags content_tag_sets content_markers content_reviews external_works media_sources ``` The backup structure must be deterministic. Records should be ordered by stable identifiers where possible: ```text id uuid timecreated sortorder ``` --- ## 6. Activity instance backup Required table: ```text uckkarchive ``` The activity instance backup preserves: ```text id course name intro introformat configuration fields default visibility default archive policy default media policy default advisory policy completion configuration timecreated timemodified ``` Restore rule: ```text The restored uckkarchive record receives a new local id. The restored activity keeps a stable uuid when appropriate. Course and course module references are remapped by Moodle restore. ``` --- ## 7. Archive item backup Required table: ```text uckkarchive_item ``` Archive item backup preserves: ```text id uuid uckkarchiveid userid title description descriptionformat type status visibility validationstate provenance sourcecomponent sourceid sortorder metadata timecreated timemodified ``` Archive item restore must: ```text map uckkarchiveid to the restored activity id map userid through Moodle user mapping when available preserve uuid unless restore policy explicitly regenerates it preserve status preserve validation state preserve visibility preserve provenance preserve metadata ``` Restore must not convert archive items into grades, official decisions, or external workflow records. --- ## 8. Proof backup Required table: ```text uckkarchive_proof ``` Proof backup preserves: ```text id uuid uckkarchiveid itemid userid type status visibility validationstate description descriptionformat metadata timecreated timemodified ``` Proof restore must: ```text map uckkarchiveid map itemid map userid restore proof file areas preserve restricted flags preserve validation state preserve provenance ``` Proof records remain archive evidence. They do not become gradebook records, integrity findings, or Assembly decisions. --- ## 9. Kristal backup Required table: ```text uckkarchive_kristal ``` Kristal backup preserves: ```text id uuid uckkarchiveid itemid userid title summary summaryformat status visibility validationstate metadata timecreated timemodified ``` Kristal restore must: ```text map uckkarchiveid map itemid when linked map userid restore Kristal file areas preserve visibility preserve validation state preserve provenance ``` Kristals remain archive-owned learning/memory objects. --- ## 10. Provenance backup Required table: ```text uckkarchive_prov ``` Provenance backup preserves: ```text id uuid uckkarchiveid targettype targetid targetuuid provenancetype sourcecomponent sourceid sourceuuid actorid description descriptionformat hashvalue metadata timecreated ``` Canonical provenance values: ```text human ai_assisted imported system archive assembly challenge integrity media external_work content_review ``` Provenance restore must: ```text map target ids when target objects are restored map actorid through Moodle user mapping when available preserve targetuuid preserve sourcecomponent preserve sourceid/sourceuuid as reference metadata preserve hash values preserve metadata ``` Provenance rule: ```text Provenance explains origin. Provenance does not grant authority by itself. ``` --- ## 11. Revision backup Required table: ```text uckkarchive_rev ``` Revision backup preserves: ```text id uuid uckkarchiveid targettype targetid targetuuid revisionnumber userid summary summaryformat changedata metadata timecreated ``` Revision restore must: ```text map target ids map userid preserve revision numbers preserve changedata preserve targetuuid ``` Archive revision permission uses: ```text mod/uckkarchive:reviseitem ``` The removed capability must not be restored or referenced: ```text mod/uckkarchive:versionitem ``` --- ## 12. Export metadata backup Required table: ```text uckkarchive_export ``` Export metadata backup preserves: ```text id uuid uckkarchiveid userid exporttype status visibility redactionlevel manifestjson metadata timecreated timemodified ``` Export package files are restored only through Moodle File API file areas. Export restore must: ```text map uckkarchiveid map userid restore export metadata restore export_manifest file area when included restore export_package file area when included and allowed preserve manifest references preserve redaction level preserve restricted flags ``` Restore must not make restricted exports public. --- ## 13. Media object backup Required table: ```text uckkarchive_media ``` Media backup preserves: ```text id uuid uckkarchiveid userid title description descriptionformat mediatype mimetype status visibility audiencesuitability sourceid currentversionid metadata timecreated timemodified ``` Canonical media states: ```text draft submitted active restricted superseded archived deleted_soft ``` Restore must: ```text map uckkarchiveid map userid map sourceid map currentversionid after media versions are restored preserve uuid preserve status preserve visibility preserve audience suitability preserve metadata ``` Media restore must not assume file availability means media availability. Media status remains authoritative. --- ## 14. Media version backup Required table: ```text uckkarchive_media_version ``` Media version backup preserves: ```text id uuid mediaid versionnumber userid status mimetype filesize contenthash filearea filename description descriptionformat metadata timecreated ``` Media version restore must: ```text map mediaid map userid preserve uuid preserve versionnumber preserve contenthash restore related File API files preserve filearea and filename references ``` Media versioning permission uses: ```text mod/uckkarchive:versionmedia ``` Media versions must remain connected to their parent media object. --- ## 15. Media relation backup Required table: ```text uckkarchive_media_relation ``` Media relation backup preserves: ```text id uuid uckkarchiveid frommediaid tomediaid fromuuid touuid relationtype targettype targetid targetuuid metadata timecreated ``` Canonical relation types: ```text belongs_to_item belongs_to_kristal belongs_to_collection is_derivative_of is_translation_of is_excerpt_of is_proof_for is_source_for replaces references duplicates references_external_work contains_content_marker ``` Restore must: ```text map frommediaid map tomediaid map targetid when target is restored preserve fromuuid preserve touuid preserve targetuuid preserve relationtype ``` Relation rule: ```text Relations describe media graph meaning. Relations do not transfer ownership to external plugins or external rights holders. ``` --- ## 16. Media tag backup Required table: ```text uckkarchive_media_tag ``` Media tag backup preserves: ```text id uuid mediaid tagkey tagvalue tagtype userid metadata timecreated ``` Restore must: ```text map mediaid map userid preserve tagkey preserve tagvalue preserve tagtype preserve metadata ``` Media tags are descriptive. Content advisories and cultural protocol tags belong to the content advisory subsystem when they affect suitability, restriction, teaching context, or review state. --- ## 17. Media collection backup Required tables: ```text uckkarchive_media_collection uckkarchive_media_collection_item ``` Collection backup preserves: ```text id uuid uckkarchiveid userid title description descriptionformat visibility status metadata timecreated timemodified ``` Collection item backup preserves: ```text id collectionid mediaid sortorder metadata timecreated ``` Restore must: ```text map uckkarchiveid map userid map collectionid map mediaid preserve uuid preserve sortorder preserve visibility preserve status ``` Collections remain archive/media-library structures. They do not become Moodle course sections or external library records. --- ## 18. Content tag backup Required table: ```text uckkarchive_content_tag ``` Content tag backup preserves: ```text id uuid tagkey name description descriptionformat tagtype severity audiencesuitability status metadata timecreated timemodified ``` Content advisory tag examples: ```text sexual_violence violence racism colonial_violence death self_harm substance_use nudity explicit_language culturally_sensitive sacred_content ceremonial_content restricted_knowledge grief_or_mourning requires_context not_for_children ``` Restore must: ```text preserve tagkey preserve severity preserve audience suitability preserve cultural protocol metadata preserve status ``` Content advisory rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 19. Content tag set backup Required table: ```text uckkarchive_content_tag_set ``` Content tag set backup preserves: ```text id uuid setkey name description descriptionformat status metadata timecreated timemodified ``` Examples: ```text general_advisories cultural_protocols classroom_suitability integrity_sensitive youth_access ``` Restore must: ```text preserve setkey preserve status preserve metadata reconnect included tags when membership is represented ``` Tag set rule: ```text Tag sets organize advisory vocabulary. Tag sets do not decide access alone. Access decisions belong to policy classes. ``` --- ## 20. Content marker backup Required table: ```text uckkarchive_content_marker ``` Content marker backup preserves: ```text id uuid uckkarchiveid tagid taguuid targettype targetid targetuuid externalworkid externalworkuuid locator_type locator_start locator_end locator_label description descriptionformat severity audiencesuitability reviewstate metadata timecreated timemodified ``` Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Restore must: ```text map uckkarchiveid map tagid map targetid when target is restored map externalworkid when external work is restored preserve taguuid preserve targetuuid preserve externalworkuuid preserve locator fields preserve severity preserve audience suitability preserve review state ``` Content marker rule: ```text A content marker locates advisory meaning. A content marker does not copy external content. A content marker does not transfer external rights. ``` --- ## 21. Content review backup Required table: ```text uckkarchive_content_review ``` Content review backup preserves: ```text id uuid markerid markeruuid reviewerid reviewstate reviewnote reviewnoteformat decision metadata timecreated timemodified ``` Content review states: ```text draft pending_review reviewed approved contested retired ``` Restore must: ```text map markerid map reviewerid through Moodle user mapping when available preserve markeruuid preserve reviewstate preserve decision preserve review notes according to privacy/redaction policy restore review file areas when included ``` Review rule: ```text AI may suggest tags or markers. Human review is required before advisory status becomes approved. AI cannot approve cultural protocol access. AI cannot remove cultural restrictions. ``` --- ## 22. External work backup Required table: ```text uckkarchive_external_work ``` External work backup preserves: ```text id uuid worktype title creator publisher publicationdate identifier identifier_type url citation citationformat rightsstatement sourceownership metadata timecreated timemodified ``` External work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` Restore must: ```text preserve uuid preserve citation metadata preserve rights metadata preserve source ownership preserve URL/reference fields restore reference files only when allowed ``` External work rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. The archive must not store unauthorized copies of external works. ``` --- ## 23. Media source backup Required table: ```text uckkarchive_media_source ``` Media source backup preserves: ```text id uuid mediaid externalworkid sourcetype sourceownership license rightsstatement attribution url metadata timecreated timemodified ``` Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Restore must: ```text map mediaid map externalworkid preserve source type preserve source ownership preserve license and rights metadata ``` Media source rule: ```text Media source describes origin and rights context. Media source does not grant access by itself. Media source does not override policy, visibility, retention, redaction, or cultural protocol rules. ``` --- ## 24. File API backup All files must be backed up and restored through Moodle File API. Component: ```text mod_uckkarchive ``` Canonical archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Canonical content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File backup rule: ```text File areas are declared centrally in classes/local/file_area_registry.php. Backup and restore must use the same registry. No production archive/media files are backed up from unmanaged public folders. ``` --- ## 25. File restore behavior File restore must: ```text restore files into the restored module context map item ids where Moodle File API itemids are tied to restored records preserve filenames preserve content hashes preserve author metadata where permitted preserve license metadata where permitted preserve timecreated and timemodified where supported ``` File restore must not: ```text make restricted files public make culturally restricted files public restore unauthorized external work copies write files outside Moodle File API create direct public URLs as authority ``` File existence does not grant access. Access remains controlled by policy classes. --- ## 26. User mapping Backup may include user-related fields such as: ```text userid actorid reviewerid creatorid modifierid ``` Restore must map users through Moodle restore user mapping. If a user cannot be mapped, restore must preserve record integrity using safe fallback behavior: ```text use restored mapped user when available use current restoring user only where Moodle restore policy allows use null or system marker when allowed by schema and policy preserve original user metadata only when privacy policy allows ``` User mapping must not reveal private user data beyond Moodle restore policy. --- ## 27. Context mapping Restore must remap: ```text course id course module id context id activity instance id archive item ids media ids media version ids collection ids content tag ids content marker ids content review ids external work ids file item ids ``` Context mapping rule: ```text Local database ids change during restore. UUIDs remain stable unless restore policy explicitly regenerates them. Relations must be reconnected using mapped ids and preserved UUIDs. ``` --- ## 28. UUID behavior UUIDs provide stable portable identity. UUIDs are required for: ```text archive items proofs Kristals provenance records revisions exports media objects media versions media collections media relations content tags content tag sets content markers content reviews external works media sources export packages ``` Restore UUID policy: ```text Default restore preserves UUIDs for portability. Duplicate-into-same-context restore may regenerate UUIDs if collision prevention requires it. Any UUID regeneration must update all internal relations and manifest references. ``` --- ## 29. Restricted records Restricted records include: ```text restricted archive items restricted media restricted integrity records restricted cultural records staff-only review notes redacted export packages content markers with restricted suitability external work references with restricted access ``` Restore rule: ```text Restricted status must survive backup and restore. Restore must never downgrade restricted visibility to public. Restore must never bypass cultural protocol restrictions. Restore must never expose restricted review notes to unauthorized roles. ``` --- ## 30. Cultural protocol restore Cultural protocol metadata may include: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Restore must preserve: ```text cultural protocol tags cultural protocol file areas cultural review state audience suitability restriction flags export restrictions ``` Cultural protocol restore rule: ```text Restored cultural protocol restrictions remain active. Restore must not transform cultural protocol notes into public metadata. ``` --- ## 31. Content advisory restore Content advisories may affect: ```text display warnings teaching context audience suitability access prompts restricted visibility cultural protocol review export filtering review workflow redaction decisions ``` Restore must preserve: ```text content tag keys content tag sets content markers locators severity audience suitability review state review decisions review notes external work references ``` Content advisory restore rule: ```text A restored advisory remains advisory metadata. It does not ban media by itself. It must still be interpreted by content_policy.php. ``` --- ## 32. External work restore External work records are references. Restore must preserve: ```text citation identifier URL rights statement source ownership locator references advisory markers teaching metadata ``` Restore must not: ```text copy external media unless the original backup lawfully contained a permitted file imply UCKK ownership turn an external reference into UCKK-created media erase source ownership ``` External work restore rule: ```text External works remain external after restore. ``` --- ## 33. Encoded links Backup task must define encoded link handling for internal module URLs. Internal links may include: ```text view.php?id=$cmid item.php?id=$cmid&itemid=$itemid media.php?id=$cmid&mediaid=$mediaid validate.php?id=$cmid&itemid=$itemid export.php?id=$cmid&exportid=$exportid ``` Restore must decode internal links to point to restored course-module and record IDs. Encoded link restore must: ```text map course module id map archive item id map media id map export id preserve external URLs as external URLs not rewrite external work references into local files ``` --- ## 34. Manifest restore Canonical manifest filename: ```text manifest.json ``` Export manifests may include: ```text plugin component archive id export id export timestamp export actor export reason archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Restore must preserve manifest files and metadata when included in the backup. Restore must not treat a manifest as an authority override. --- ## 35. Privacy interaction Backup and restore must respect Moodle privacy expectations. Privacy-sensitive data may include: ```text user-created archive items proof records private media restricted metadata review notes content reviews cultural protocol notes provenance actor data revision actor data export actor data file author metadata ``` Privacy restore rule: ```text Restored data remains subject to mod_uckkarchive privacy provider behavior. Backup/restore does not bypass privacy export, deletion, retention, or redaction policy. ``` --- ## 36. Redaction behavior Backup may include redacted and unredacted records depending on Moodle backup context and permissions. Restore must preserve: ```text redaction level restricted flags visibility review state audience suitability cultural protocol flags export restrictions ``` Restore must not: ```text reconstruct redacted fields from export summaries make redacted metadata visible erase redaction state convert restricted records into ordinary public records ``` Redaction rule: ```text Redaction state is data. It must be restored as part of the archive record. ``` --- ## 37. Optional integration behavior Optional integrations include: ```text tool_uckkintegrity mod_uckkchallenge mod_uckkassembly report_uckk local_uckk ``` Restore behavior: ```text If optional plugins are present, restored references may be resolvable. If optional plugins are absent, restored references remain preserved metadata. Ordinary archive/media/content-advisory operation must continue. Integrity-specific features must be hidden, disabled, or fail closed when tool_uckkintegrity is absent. ``` Restore must not require optional plugins for core archive/media restore. --- ## 38. Restore order Recommended restore order: ```text 1. uckkarchive activity instance 2. archive items 3. proofs 4. Kristals 5. media sources that do not depend on media 6. external works 7. media objects 8. media versions 9. media collections 10. media collection items 11. media tags 12. media relations 13. content tags 14. content tag sets 15. content markers 16. content reviews 17. provenance records 18. revision records 19. export metadata 20. File API files 21. encoded links 22. post-restore relation repair 23. post-restore current-version repair ``` Ordering rule: ```text Records that provide identities must be restored before records that reference them. Post-restore repair must reconnect relations that require mapped ids. ``` --- ## 39. Post-restore repair Post-restore repair must verify: ```text current media version references media relation endpoints collection membership content marker targets content review marker links external work links media source links archive item links proof links Kristal links provenance target links revision target links export manifest references File API itemids ``` Post-restore repair must not invent missing external authority records. --- ## 40. Failure handling Restore should fail safely. Safe failure behavior: ```text do not expose restricted data do not publish culturally restricted data do not create public file links do not discard provenance silently do not discard content advisories silently do not discard external work rights metadata silently do not convert broken references into owned records ``` When restore cannot resolve a relation, it should preserve: ```text targetuuid sourcecomponent sourceid external identifier metadata human-readable reference ``` --- ## 41. Scheduled task interaction Backup/restore may affect scheduled tasks. Relevant task files: ```text classes/task/generate_archive_exports.php classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/purge_expired_exports.php classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php classes/task/validate_pending_items.php ``` Restore rule: ```text Restore may mark search indexes, thumbnails, derivatives, and advisory indexes for rebuild. Restore must not run privileged generation that bypasses policy. ``` --- ## 42. Events and audit interaction Restore may create Moodle restore logs. Restore must not emit normal user action events as if users manually created every restored record. Audit-sensitive restored data includes: ```text archive provenance media provenance content reviews validation state restricted records export metadata ``` Audit rule: ```text Restore metadata must distinguish restored records from newly created user actions. ``` --- ## 43. Testing requirements Required backup/restore tests: ```text tests/backup_restore_test.php tests/file_api_test.php tests/media_library_test.php tests/content_advisory_test.php tests/external_work_test.php tests/privacy_provider_test.php ``` Test coverage must verify: ```text activity instance backup and restore archive item backup and restore media object backup and restore media version backup and restore media collection backup and restore media relation backup and restore content tag backup and restore content tag set backup and restore content marker backup and restore content review backup and restore external work backup and restore media source backup and restore File API file restore restricted visibility preservation cultural protocol restriction preservation UUID preservation ID remapping manifest preservation optional integration absence behavior ``` Testing rule: ```text Tests verify final target behavior, not historical transitions. ``` --- ## 44. Non-goals Backup/restore must not: ```text backup raw public folder files as archive authority restore unauthorized third-party media copies create grades create transcripts create enrolments create global registry authority create challenge workflow state create Assembly decision authority create integrity case authority create institutional report authority bypass Moodle File API bypass Moodle Privacy API bypass Moodle capabilities bypass policy classes ``` --- ## 45. Final backup/restore rule ```text mod_uckkarchive backup and restore preserve archive memory, media library objects, content advisories, cultural protocol metadata, external work references, media source records, provenance, revisions, validation state, restricted metadata, File API files, and export manifests. Restore reconstructs module-owned state in the restored Moodle activity context. Restore does not create grades, transcripts, enrolments, registry authority, challenge workflow authority, Assembly decision authority, integrity case authority, institutional reporting authority, or third-party ownership rights. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/13_services_and_ajax_api.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 0dc1e4b9468278c4f9450f02e54c6ccb4f9081899dee516ea658d3c30b3fa7c9 CONTENT_BYTES: 34090 ================================================================================================ # 13 — Services and AJAX API **Path:** `docs/13_services_and_ajax_api.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** External services, AJAX APIs, service-layer rules, request/response contracts, and server-side authority for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Purpose This document defines the final service and AJAX API architecture for `mod_uckkarchive`. The module is: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` The service layer exposes controlled Moodle external functions for: ```text archive items media objects media versions media collections media relations media tags content advisories content tag sets content markers content reviews external works proofs Kristals provenance panels validation panels restricted views exports rendered cards and panels ``` Services are not simple data access endpoints. Services are authority gates. --- ## 2. Service architecture rule Every external service must: ```text resolve Moodle context validate parameters require login when needed check sesskey where required check capability gates apply archive/media/content policy filter output by visibility and restriction apply privacy and redaction rules validate lifecycle state avoid leaking restricted metadata return stable structured payloads emit events only after successful state changes ``` No AJAX or external function may bypass: ```text classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php classes/local/context_resolver.php classes/local/file_area_registry.php ``` --- ## 3. Moodle service registration External service functions are declared in: ```text db/services.php ``` Service implementation classes are stored in: ```text classes/external/ ``` The service declaration must define: ```text classname methodname classpath description type ajax capabilities where appropriate ``` AJAX-enabled functions use: ```text 'ajax' => true ``` Service classes must follow Moodle external API conventions: ```text external_function_parameters execute execute_returns ``` --- ## 4. Naming convention Service class filenames use lower_snake_case: ```text classes/external/get_archive.php classes/external/add_media.php classes/external/review_content_marker.php ``` Class names use the Moodle component namespace: ```php mod_uckkarchive\external\get_archive mod_uckkarchive\external\add_media mod_uckkarchive\external\review_content_marker ``` Function naming rule: ```text get_* = read search_* = filtered read add_* = create update_* = update delete_* = soft delete or controlled removal remove_* = relation or membership removal review_* = human review action export_* = export creation/request ``` --- ## 5. Context resolution All services must resolve context through: ```text classes/local/context_resolver.php ``` Supported resolution inputs: ```text cmid courseid archiveid itemid mediaid mediauuid collectionid externalworkid contentmarkerid ``` Resolution must produce, as applicable: ```text context_module course cm uckkarchive instance archive item media object media version media collection content marker external work ``` Context rule: ```text Services must not manually reconstruct context resolution in each endpoint. ``` --- ## 6. Common request fields Most services accept one or more of: ```text cmid courseid archiveid itemid itemuuid mediaid mediauuid versionid versionuuid collectionid collectionuuid contentmarkerid contentmarkeruuid externalworkid externalworkuuid page perpage sort direction filters include ``` Pagination defaults: ```text page = 0 perpage = 20 maximum_perpage = 100 ``` Sorting defaults: ```text sort = timemodified direction = desc ``` --- ## 7. Common response fields Read/list services return: ```text status warnings data pagination permissions ``` Create/update services return: ```text status warnings record permissions events ``` Rendered-card services return: ```text status warnings html data permissions ``` Export services return: ```text status warnings exportid exportuuid state downloadurl manifest ``` Error responses must use Moodle exceptions where appropriate: ```text required_capability_exception invalid_parameter_exception moodle_exception invalid_response_exception ``` --- ## 8. Permission payload rule Service responses may include permission summaries for UI convenience. Example: ```json { "permissions": { "canview": true, "canedit": false, "candelete": false, "canexport": true, "canviewrestricted": false, "canreviewadvisories": false } } ``` Permission summaries are not authority. The server must re-check policy on every action. --- ## 9. Archive service files ```text classes/external/get_archive.php classes/external/get_archive_items.php classes/external/get_archive_item.php classes/external/get_archive_item_card.php classes/external/get_proofs.php classes/external/get_provenance_panel.php classes/external/get_kristal.php classes/external/get_revisions.php classes/external/get_restricted_item.php classes/external/save_item_draft.php classes/external/add_item.php classes/external/add_proof.php classes/external/update_provenance.php classes/external/validate_item.php classes/external/revise_item.php classes/external/create_kristal.php classes/external/update_kristal.php ``` Archive services must enforce: ```text mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Archive service policy source: ```text classes/local/archive_policy.php ``` --- ## 10. `get_archive` Path: ```text classes/external/get_archive.php ``` Purpose: ```text Return the main archive activity state for the current user. ``` Parameters: ```text cmid include ``` Allowed include values: ```text summary counts permissions recent_items collections_summary advisory_summary export_summary ``` Returns: ```text archive counts recentitems permissions warnings ``` Rules: ```text Only permission-visible summary data is returned. Restricted counts may be rounded, hidden, or omitted depending on policy. ``` --- ## 11. `get_archive_items` Path: ```text classes/external/get_archive_items.php ``` Purpose: ```text Return a filtered, permission-aware list of archive items. ``` Parameters: ```text cmid filters page perpage sort direction ``` Supported filters: ```text status validationstate visibility type ownerid tag hasmedia hasadvisory hasrestricted provenance timemodifiedfrom timemodifiedto ``` Returns: ```text items pagination permissions warnings ``` Rules: ```text Restricted items are excluded unless the user has authority. Fields inside visible items are redacted when needed. ``` --- ## 12. `get_archive_item` Path: ```text classes/external/get_archive_item.php ``` Purpose: ```text Return one archive item with permission-filtered metadata. ``` Parameters: ```text cmid itemid itemuuid include ``` Allowed include values: ```text files proofs media provenance revisions validation advisories collections permissions ``` Returns: ```text item files proofs media provenance revisions validation advisories permissions warnings ``` Rules: ```text The service must not return restricted file URLs, restricted notes, private review data, or cultural protocol details without authority. ``` --- ## 13. `get_archive_item_card` Path: ```text classes/external/get_archive_item_card.php ``` Purpose: ```text Return rendered HTML and matching structured data for one archive item card. ``` Parameters: ```text cmid itemid itemuuid ``` Returns: ```text html item permissions warnings ``` Rendering source: ```text classes/output/archive_item_card.php templates/archive_item_card.mustache ``` Rules: ```text The card must be generated from permission-filtered data only. ``` --- ## 14. `save_item_draft` Path: ```text classes/external/save_item_draft.php ``` Purpose: ```text Create or update a draft archive item. ``` Parameters: ```text cmid itemid title summary content type visibility metadata ``` Returns: ```text item permissions warnings ``` Rules: ```text Drafts are visible only according to ownership and role policy. Draft save does not validate the item. ``` --- ## 15. `add_item` Path: ```text classes/external/add_item.php ``` Purpose: ```text Create a non-draft archive item or submit a draft archive item. ``` Parameters: ```text cmid title summary content type visibility metadata mediauuids contentmarkeruuids ``` Returns: ```text item permissions warnings ``` Events: ```text classes/event/archive_item_created.php ``` Rules: ```text Creation must assign UUID, provenance, status, visibility, owner, and context. ``` --- ## 16. `validate_item` Path: ```text classes/external/validate_item.php ``` Purpose: ```text Apply a human validation decision to an archive item. ``` Parameters: ```text cmid itemid validationstate validationnote visibility restrictionstate ``` Allowed validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Returns: ```text item validation permissions warnings ``` Events: ```text classes/event/archive_item_validated.php ``` Rules: ```text Validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. ``` --- ## 17. `revise_item` Path: ```text classes/external/revise_item.php ``` Purpose: ```text Create an archive item revision. ``` Parameters: ```text cmid itemid revisiontitle revisionnote fields ``` Returns: ```text item revision permissions warnings ``` Capability: ```text mod/uckkarchive:reviseitem ``` Rules: ```text The module does not use mod/uckkarchive:versionitem. Archive item revision authority is mod/uckkarchive:reviseitem. ``` --- ## 18. Media service files ```text classes/external/get_media.php classes/external/get_media_item.php classes/external/get_media_card.php classes/external/search_media.php classes/external/add_media.php classes/external/update_media.php classes/external/delete_media.php classes/external/add_media_version.php classes/external/get_media_versions.php classes/external/get_media_relations.php classes/external/add_media_relation.php classes/external/remove_media_relation.php classes/external/get_media_collections.php classes/external/get_media_collection.php classes/external/add_media_collection.php classes/external/update_media_collection.php classes/external/add_media_to_collection.php classes/external/remove_media_from_collection.php classes/external/tag_media.php classes/external/untag_media.php ``` Media services must enforce: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Media service policy source: ```text classes/local/media_policy.php ``` --- ## 19. `get_media` Path: ```text classes/external/get_media.php ``` Purpose: ```text Return a filtered, permission-aware media library list. ``` Parameters: ```text cmid filters page perpage sort direction include ``` Supported filters: ```text mediatype status visibility source ownerid tag contenttag collectionid hasadvisory hasrestricted hastranscript hascaption hasthumbnail createdfrom createdto modifiedfrom modifiedto ``` Returns: ```text media pagination permissions warnings ``` Rules: ```text Media objects are returned only if viewable. Restricted fields are redacted before response construction. ``` --- ## 20. `search_media` Path: ```text classes/external/search_media.php ``` Purpose: ```text Search media metadata, tags, collections, sources, and approved content advisory metadata. ``` Parameters: ```text cmid query filters page perpage ``` Returns: ```text results pagination permissions warnings ``` Rules: ```text Search must not reveal the existence of restricted media to unauthorized users. Search indexing must respect content policy and visibility. ``` --- ## 21. `get_media_item` Path: ```text classes/external/get_media_item.php ``` Purpose: ```text Return one media object with versions, files, source, advisories, and relations when authorized. ``` Parameters: ```text cmid mediaid mediauuid include ``` Allowed include values: ```text versions files relations collections tags source advisories reviews permissions ``` Returns: ```text media versions files relations collections tags source advisories permissions warnings ``` Rules: ```text Original file download URLs require download authority. Preview and thumbnail URLs require view authority. Restricted media requires restricted media authority. Culturally restricted fields require cultural protocol authority. ``` --- ## 22. `get_media_card` Path: ```text classes/external/get_media_card.php ``` Purpose: ```text Return rendered HTML and structured data for one media card. ``` Parameters: ```text cmid mediaid mediauuid ``` Returns: ```text html media permissions warnings ``` Rendering source: ```text classes/output/media_card.php templates/media_card.mustache ``` Rules: ```text The card may show advisory badges only if the advisory policy allows them. The card must not show hidden cultural notes to unauthorized users. ``` --- ## 23. `add_media` Path: ```text classes/external/add_media.php ``` Purpose: ```text Create a media object and initial media version. ``` Parameters: ```text cmid title description mediatype visibility source metadata draftitemid ``` Returns: ```text media version permissions warnings ``` Events: ```text classes/event/media_created.php classes/event/media_version_created.php ``` Rules: ```text The service creates a stable media UUID. The service creates a stable media version UUID. The uploaded file is stored in the appropriate Moodle File API area. ``` --- ## 24. `update_media` Path: ```text classes/external/update_media.php ``` Purpose: ```text Update media metadata, lifecycle state, source classification, or visibility. ``` Parameters: ```text cmid mediaid mediauuid fields ``` Returns: ```text media permissions warnings ``` Events: ```text classes/event/media_updated.php ``` Rules: ```text Metadata update does not overwrite original files. File changes require media versioning. ``` --- ## 25. `delete_media` Path: ```text classes/external/delete_media.php ``` Purpose: ```text Soft-delete or controlled-remove a media object. ``` Parameters: ```text cmid mediaid mediauuid reason ``` Returns: ```text media state warnings ``` Rules: ```text Default deletion is deleted_soft. Retention, provenance, export history, validation links, and content advisories must be preserved according to policy. ``` --- ## 26. `add_media_version` Path: ```text classes/external/add_media_version.php ``` Purpose: ```text Create a new version for an existing media object. ``` Parameters: ```text cmid mediaid mediauuid versionnote draftitemid metadata ``` Returns: ```text media version permissions warnings ``` Capability: ```text mod/uckkarchive:versionmedia ``` Events: ```text classes/event/media_version_created.php ``` Rules: ```text Media files are not silently overwritten. Replacement or correction creates a version record. ``` --- ## 27. Media relation services Files: ```text classes/external/get_media_relations.php classes/external/add_media_relation.php classes/external/remove_media_relation.php ``` Canonical relation types: ```text belongs_to_item belongs_to_kristal belongs_to_collection is_derivative_of is_translation_of is_excerpt_of is_proof_for is_source_for replaces references duplicates references_external_work contains_content_marker ``` Rules: ```text Relations describe graph meaning. Relations do not transfer ownership. Relations must not create unauthorized visibility. ``` --- ## 28. Media collection services Files: ```text classes/external/get_media_collections.php classes/external/get_media_collection.php classes/external/add_media_collection.php classes/external/update_media_collection.php classes/external/add_media_to_collection.php classes/external/remove_media_from_collection.php ``` Collection service rules: ```text Collections group media objects without duplicating files. Collection visibility cannot make restricted media public. Collection export requires export authority for each included object. ``` --- ## 29. Media tag services Files: ```text classes/external/tag_media.php classes/external/untag_media.php ``` Rules: ```text Media tags describe media organization. Content advisory tags describe suitability, cultural sensitivity, and warning conditions. Do not merge media tags and content advisory tags into one authority model. ``` --- ## 30. Content advisory service files ```text classes/external/get_content_tags.php classes/external/get_content_tag_sets.php classes/external/get_content_markers.php classes/external/add_content_marker.php classes/external/update_content_marker.php classes/external/delete_content_marker.php classes/external/review_content_marker.php ``` Content advisory services must enforce: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted ``` Content policy source: ```text classes/local/content_policy.php ``` --- ## 31. `get_content_tags` Path: ```text classes/external/get_content_tags.php ``` Purpose: ```text Return available content advisory and cultural protocol tags. ``` Parameters: ```text cmid tagset includeinactive ``` Returns: ```text tags tagsets permissions warnings ``` Rules: ```text Culturally restricted tag definitions may be hidden or summarized depending on policy. ``` --- ## 32. `get_content_tag_sets` Path: ```text classes/external/get_content_tag_sets.php ``` Purpose: ```text Return reusable advisory vocabularies. ``` Canonical tag set examples: ```text general_advisories cultural_protocols classroom_suitability integrity_sensitive youth_access ``` Returns: ```text tagsets permissions warnings ``` Rules: ```text Tag sets support controlled vocabularies. They do not replace review policy. ``` --- ## 33. `get_content_markers` Path: ```text classes/external/get_content_markers.php ``` Purpose: ```text Return content advisory markers for media, archive items, media versions, or external works. ``` Parameters: ```text cmid mediaid mediauuid itemid itemuuid externalworkid externalworkuuid filters ``` Returns: ```text markers permissions warnings ``` Supported locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Rules: ```text Markers must be filtered by review state, audience suitability, visibility, and cultural protocol policy. ``` --- ## 34. `add_content_marker` Path: ```text classes/external/add_content_marker.php ``` Purpose: ```text Add a content advisory marker to an internal media object, archive item, media version, or external work. ``` Parameters: ```text cmid targettype targetid targetuuid tagkeys locator_type locator_start locator_end description severity audience_suitability cultural_protocol review_required ``` Returns: ```text marker permissions warnings ``` Events: ```text classes/event/content_marker_created.php ``` Rules: ```text AI may suggest a marker. Human review is required before advisory status becomes approved. ``` --- ## 35. `update_content_marker` Path: ```text classes/external/update_content_marker.php ``` Purpose: ```text Update marker tags, locator, severity, suitability, or description. ``` Parameters: ```text cmid contentmarkerid contentmarkeruuid fields ``` Returns: ```text marker permissions warnings ``` Rules: ```text Changing a reviewed marker may return it to pending_review depending on policy. ``` --- ## 36. `delete_content_marker` Path: ```text classes/external/delete_content_marker.php ``` Purpose: ```text Retire or soft-delete a content marker. ``` Parameters: ```text cmid contentmarkerid contentmarkeruuid reason ``` Returns: ```text marker state warnings ``` Rules: ```text The system preserves review and provenance history. ``` --- ## 37. `review_content_marker` Path: ```text classes/external/review_content_marker.php ``` Purpose: ```text Record human review of a content marker, advisory tag, suitability value, or cultural protocol note. ``` Parameters: ```text cmid contentmarkerid contentmarkeruuid reviewstate reviewnote audience_suitability restriction ``` Allowed review states: ```text draft pending_review reviewed approved contested retired ``` Returns: ```text marker review permissions warnings ``` Events: ```text classes/event/content_marker_reviewed.php ``` Rules: ```text AI cannot approve cultural protocol access. AI cannot mark culturally restricted content as safe. AI cannot close contestations. ``` --- ## 38. External work service files ```text classes/external/get_external_works.php classes/external/get_external_work.php classes/external/add_external_work.php classes/external/update_external_work.php ``` External work services must enforce: ```text mod/uckkarchive:manageexternalworks mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories ``` External work policy source: ```text classes/local/external_work.php classes/local/content_policy.php ``` --- ## 39. `get_external_works` Path: ```text classes/external/get_external_works.php ``` Purpose: ```text Return a filtered list of referenced external or foreign works. ``` Parameters: ```text cmid query filters page perpage sort direction ``` Supported work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` Returns: ```text externalworks pagination permissions warnings ``` Rules: ```text The archive may reference foreign media without copying it. The response must not imply UCKK ownership of third-party works. ``` --- ## 40. `get_external_work` Path: ```text classes/external/get_external_work.php ``` Purpose: ```text Return one external work reference with permission-filtered metadata and advisory markers. ``` Parameters: ```text cmid externalworkid externalworkuuid include ``` Allowed include values: ```text markers reviews relations permissions ``` Returns: ```text externalwork markers relations permissions warnings ``` Rules: ```text External work services may return metadata, teaching notes, locators, and content advisories. They must not store or expose unauthorized copies of third-party content. ``` --- ## 41. `add_external_work` Path: ```text classes/external/add_external_work.php ``` Purpose: ```text Create an external work reference. ``` Parameters: ```text cmid title worktype creator publisher publicationdate identifier url citation source_ownership rights_note metadata ``` Returns: ```text externalwork permissions warnings ``` Events: ```text classes/event/external_work_created.php ``` Rules: ```text External work creation stores reference metadata and source classification. It does not import third-party content unless a separate authorized media object is created. ``` --- ## 42. Export service files ```text classes/external/get_export_preview.php classes/external/export_items.php classes/external/export_media.php classes/external/export_collection.php classes/external/get_export_status.php ``` Export service policy sources: ```text classes/local/export_package.php classes/local/manifest_builder.php classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php ``` Export services must enforce: ```text mod/uckkarchive:export mod/uckkarchive:exportmedia mod/uckkarchive:viewrestricted mod/uckkarchive:viewrestrictedmedia mod/uckkarchive:viewculturallyrestricted ``` --- ## 43. `get_export_preview` Path: ```text classes/external/get_export_preview.php ``` Purpose: ```text Return a permission-aware preview of what an export would include. ``` Parameters: ```text cmid targettype targetids options ``` Target types: ```text archive_items media_items media_collection full_archive content_advisory_package external_work_reference_package ``` Returns: ```text included excluded redacted warnings permissions ``` Rules: ```text Preview must show excluded/redacted counts without leaking restricted details. ``` --- ## 44. `export_items` Path: ```text classes/external/export_items.php ``` Purpose: ```text Create an export package for archive items. ``` Parameters: ```text cmid itemids format options reason ``` Returns: ```text exportid exportuuid state manifest downloadurl warnings ``` Rules: ```text Export includes manifest.json. Export respects validation, visibility, restricted state, retention, redaction, content advisories, and cultural protocol rules. ``` --- ## 45. `export_media` Path: ```text classes/external/export_media.php ``` Purpose: ```text Create an export package for selected media objects. ``` Parameters: ```text cmid mediaids format options reason ``` Returns: ```text exportid exportuuid state manifest downloadurl warnings ``` Rules: ```text Original files require download/export authority. Restricted media requires restricted media authority. Culturally restricted media requires cultural access authority. External references may export metadata and locators without exporting third-party content. ``` --- ## 46. `export_collection` Path: ```text classes/external/export_collection.php ``` Purpose: ```text Create an export package for a media collection. ``` Parameters: ```text cmid collectionid collectionuuid format options reason ``` Returns: ```text exportid exportuuid state manifest downloadurl warnings ``` Rules: ```text Collection export checks every included media object individually. Collection membership does not grant export authority. ``` --- ## 47. `get_export_status` Path: ```text classes/external/get_export_status.php ``` Purpose: ```text Return the current status of an export package. ``` Parameters: ```text cmid exportid exportuuid ``` Returns: ```text exportid exportuuid state progress downloadurl manifest warnings ``` Allowed states: ```text queued running ready failed expired purged ``` Rules: ```text Download URL is returned only if the user still has authority to access the export. ``` --- ## 48. Rendered panel services Rendered panel services return HTML generated through output classes and Mustache templates. Required panel/card services: ```text classes/external/get_archive_item_card.php classes/external/get_media_card.php classes/external/get_provenance_panel.php classes/external/get_restricted_item.php ``` Optional rendered payloads may be added for: ```text content_advisory_panel external_work_card media_version_list media_relation_list validation_panel ``` Rendered service rule: ```text Rendered services must return HTML only from already-filtered data. ``` --- ## 49. File URL and download rules Services may return file metadata: ```text filename mimetype filesize timecreated timemodified contenthash where allowed filearea itemid ``` Services may return file URLs only when permitted. Rules: ```text Preview URLs require view authority. Thumbnail URLs require view authority. Original download URLs require download authority. Export package URLs require export/download authority. Restricted file URLs require restricted authority. Culturally restricted file URLs require cultural protocol authority. ``` File delivery remains controlled by: ```text mod_uckkarchive_pluginfile() ``` in: ```text lib.php ``` --- ## 50. Content advisory examples A content marker for a film: ```json { "targettype": "external_work", "worktype": "film", "title": "Maïna", "tagkeys": ["sexual_violence"], "locator_type": "timecode_range", "locator_start": "01:12:30", "locator_end": "01:15:10", "severity": "strong", "audience_suitability": "mature", "reviewstate": "approved" } ``` A content marker for a book: ```json { "targettype": "external_work", "worktype": "book", "title": "The Body Keeps the Score", "tagkeys": ["sexual_violence", "requires_context"], "locator_type": "page_range", "locator_start": "42", "locator_end": "45", "severity": "strong", "audience_suitability": "guided", "reviewstate": "approved" } ``` Rules: ```text The marker records advisory metadata and locator information. It does not copy external content. It does not ban the work. It supports responsible teaching, access, review, restriction, and contextualization. ``` --- ## 51. AJAX front-end integration AMD modules call Moodle external services through Moodle’s core AJAX API. AMD files: ```text amd/src/archive.js amd/src/content_advisory.js amd/src/export.js amd/src/external_work.js amd/src/kristal.js amd/src/media.js amd/src/media_collection.js ``` AJAX rule: ```text AMD modules send requests. External services decide. ``` AMD modules must not: ```text grant access infer hidden permissions construct restricted URLs approve validation approve content advisory review approve cultural protocol access decide export authority ``` --- ## 52. Security rules Every service must protect against: ```text context confusion ID guessing UUID guessing capability bypass hidden metadata leakage restricted file URL leakage culturally restricted note leakage cross-course access cross-module access unvalidated draft publication unauthorized export unauthorized external work modification unauthorized content advisory review ``` Security rule: ```text The service layer must treat all input as untrusted. ``` --- ## 53. Privacy and redaction rules Services must apply privacy and redaction rules before response construction. Redactable fields include: ```text private notes review notes cultural protocol notes restricted metadata source identifiers user identifiers file hashes external work rights notes integrity-sensitive references download URLs export URLs ``` Privacy rule: ```text If the user cannot view a field, the field must be omitted, redacted, or summarized before output. ``` --- ## 54. Events from services Services that create or change state emit events after successful transaction completion. Event classes: ```text classes/event/archive_item_created.php classes/event/archive_item_validated.php classes/event/archive_item_revised.php classes/event/archive_item_exported.php classes/event/media_created.php classes/event/media_updated.php classes/event/media_version_created.php classes/event/media_collection_created.php classes/event/media_exported.php classes/event/content_marker_created.php classes/event/content_marker_reviewed.php classes/event/external_work_created.php ``` Event rule: ```text No event is emitted for failed or unauthorized service calls. ``` --- ## 55. Transactions State-changing services should use database transactions when writing related records. Examples: ```text media object + first version + file reference archive item + provenance + media relations content marker + review state + provenance export record + manifest + package file collection + collection items ``` Transaction rule: ```text Partial state must not be committed when a required related write fails. ``` --- ## 56. Caching Read services may use caching only when safe. Cache-sensitive data: ```text permissions visibility restricted state content advisory review state cultural protocol access file URLs export URLs ``` Caching rule: ```text Do not cache permission-filtered responses across users unless the cache key includes all relevant access dimensions. ``` --- ## 57. Validation Parameter validation must include: ```text type checks required fields allowed enum values context existence record existence record belongs to context UUID format JSON metadata shape file area validity locator type validity tag key validity visibility validity status validity review state validity ``` Validation source helpers: ```text classes/local/metadata_validator.php classes/local/uuid.php classes/local/file_area_registry.php ``` --- ## 58. Stable identifiers Services may accept local IDs or UUIDs where appropriate. Rules: ```text Local ids are used for Moodle runtime convenience. UUIDs are used for portability, restore, duplication, and export identity. Responses should include UUIDs for archive, media, version, content marker, external work, collection, and export records. ``` --- ## 59. Versioning rules Archive item revision: ```text mod/uckkarchive:reviseitem ``` Media versioning: ```text mod/uckkarchive:versionmedia ``` Removed capability: ```text mod/uckkarchive:versionitem ``` Rules: ```text Do not define or require mod/uckkarchive:versionitem. Do not silently overwrite media files. Do not silently overwrite validation history. ``` --- ## 60. Final service rule ```text External services are the controlled API surface of mod_uckkarchive. They expose archive, media, content advisory, external work, validation, provenance, revision, and export behavior through Moodle-native external functions. They must resolve context, validate input, check capabilities, apply policy, filter output, protect restricted data, emit events only after successful changes, and return stable structured payloads suitable for AMD and server-rendered UI. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/14_events_and_audit.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 3e6142996c6fd016f68ec169b6f6cb4631de5f678c2666606cb18f13690d7c01 CONTENT_BYTES: 29315 ================================================================================================ # 14 — Events and Audit **Path:** `docs/14_events_and_audit.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Moodle events, event classes, audit behavior, observer behavior, revision records, privacy-safe logging, content advisory audit, cultural protocol audit, media audit, and export audit. --- ## 1. Purpose This document defines the final event and audit architecture for `mod_uckkarchive`. `mod_uckkarchive` is a self-contained Moodle activity module for: ```text archive memory media library management content advisories cultural sensitivity tags external/foreign media references provenance validation revision history export packages ``` Events and audit records must make important actions traceable without exposing restricted content. --- ## 2. Core audit decision `mod_uckkarchive` uses two complementary audit layers: ```text Moodle Events API = activity log, user action log, system event stream uckkarchive_rev = domain revision history for meaningful state changes ``` Moodle events answer: ```text who did something where it happened when it happened what kind of action happened which object was affected ``` Revision records answer: ```text what changed why it changed which domain state changed which version is current which record supersedes another how provenance, validation, restriction, or advisory state evolved ``` Both layers are required. --- ## 3. Event architecture rule Events audit successful actions. Events do not authorize actions. Events do not validate actions. Events do not reveal restricted content. Canonical rule: ```text Authorization happens before events. Domain state changes happen before events. Events record the result. ``` An event must not be triggered for a failed permission check unless Moodle core security logging requires a separate safe event. --- ## 4. Required event files Required event classes: ```text classes/event/archive_viewed.php classes/event/archive_item_created.php classes/event/archive_item_validated.php classes/event/archive_item_revised.php classes/event/archive_item_exported.php classes/event/media_created.php classes/event/media_updated.php classes/event/media_version_created.php classes/event/media_collection_created.php classes/event/media_exported.php classes/event/content_marker_created.php classes/event/content_marker_reviewed.php classes/event/external_work_created.php ``` Required event registration file: ```text db/events.php ``` Required observer file: ```text classes/observer.php ``` Events must follow Moodle namespacing: ```text \mod_uckkarchive\event\event_name ``` --- ## 5. Event class naming Event class names use lowercase words separated by underscores. Examples: ```text archive_viewed archive_item_created archive_item_validated archive_item_revised archive_item_exported media_created media_updated media_version_created media_collection_created media_exported content_marker_created content_marker_reviewed external_work_created ``` Each class path must match the class name: ```text classes/event/media_created.php ``` Class: ```php namespace mod_uckkarchive\event; class media_created extends \core\event\base { } ``` --- ## 6. Moodle event base requirements Every event class must define: ```text init() get_name() get_description() get_url() get_objectid_mapping() get_other_mapping() ``` Where appropriate, event classes also define: ```text validate_data() ``` Each event must set: ```text context objectid userid relateduserid when applicable courseid when applicable other when needed ``` The event `other` payload must be minimal and privacy-safe. --- ## 7. Event privacy rule Events must not include: ```text raw media content file contents full archive item content private notes cultural protocol notes restricted advisory notes restricted integrity details unredacted personal data unredacted proof details full manifest JSON private source URLs confidential review text ``` Events may include: ```text record id record uuid record type status key visibility key validation state key media type key version number export type collection id marker id external work id safe tag key safe relation type ``` Rule: ```text Events identify actions. Events do not carry sensitive payloads. ``` --- ## 8. Audit authority layers Audit behavior is divided across these layers: | Layer | Role | |---|---| | Moodle Events API | Records action occurrence in Moodle logs. | | `uckkarchive_rev` | Records domain-level change history. | | `uckkarchive_prov` | Records source, origin, actor, and provenance. | | `uckkarchive_export` | Records export request, status, manifest, and expiry. | | `uckkarchive_content_review` | Records human review of content advisories and cultural protocol markers. | | Moodle File API | Stores files and supports file access logging through Moodle. | | Moodle Privacy API | Exports/deletes/anonymises user-linked data according to policy. | No layer replaces the others. --- ## 9. Archive events ### `archive_viewed` Path: ```text classes/event/archive_viewed.php ``` Triggered when a user views the main activity/archive page. Required payload: ```text contextid courseid objectid = uckkarchive.id userid other.archiveuuid ``` Must not include: ```text item content restricted item count details private user-specific notes ``` ### `archive_item_created` Path: ```text classes/event/archive_item_created.php ``` Triggered when an archive item is created. Required payload: ```text contextid courseid objectid = uckkarchive_item.id userid other.archiveid other.archiveuuid other.itemuuid other.itemtype other.status other.visibility other.validationstate ``` Associated revision: ```text uckkarchive_rev.revisiontype = item_created ``` ### `archive_item_validated` Path: ```text classes/event/archive_item_validated.php ``` Triggered when a human validation action changes validation state. Required payload: ```text contextid courseid objectid = uckkarchive_item.id userid = validator relateduserid = item owner when applicable other.itemuuid other.previousvalidationstate other.newvalidationstate other.visibility ``` Associated revision: ```text uckkarchive_rev.revisiontype = item_validation_changed ``` Validation rule: ```text Validation is human-final. AI cannot trigger final validation events as the validating authority. ``` ### `archive_item_revised` Path: ```text classes/event/archive_item_revised.php ``` Triggered when an archive item receives a new revision. Required payload: ```text contextid courseid objectid = uckkarchive_item.id userid other.itemuuid other.revisionuuid other.revisiontype other.versionno ``` Associated revision: ```text uckkarchive_rev.revisiontype = item_revised ``` ### `archive_item_exported` Path: ```text classes/event/archive_item_exported.php ``` Triggered when an archive item is included in an export package. Required payload: ```text contextid courseid objectid = uckkarchive_export.id userid other.exportuuid other.itemuuid other.exporttype other.redactionmode ``` Must not include: ```text manifestjson file paths restricted content ``` --- ## 10. Media events ### `media_created` Path: ```text classes/event/media_created.php ``` Triggered when a first-class media object is created. Required payload: ```text contextid courseid objectid = uckkarchive_media.id userid other.mediauuid other.mediatype other.status other.visibility other.audiencesuitability ``` Associated revision: ```text uckkarchive_rev.revisiontype = media_created ``` ### `media_updated` Path: ```text classes/event/media_updated.php ``` Triggered when media metadata, status, visibility, suitability, rights, source, or restriction state changes. Required payload: ```text contextid courseid objectid = uckkarchive_media.id userid other.mediauuid other.revisionuuid other.status other.visibility other.audiencesuitability ``` Associated revision: ```text uckkarchive_rev.revisiontype = media_updated ``` ### `media_version_created` Path: ```text classes/event/media_version_created.php ``` Triggered when a media version is created. Required payload: ```text contextid courseid objectid = uckkarchive_media_version.id userid other.mediaid other.mediauuid other.mediaversionuuid other.versionno other.versiontype other.filearea ``` Associated revision: ```text uckkarchive_rev.revisiontype = media_version_created ``` Must not include: ```text file content direct file URL contenthash if restricted private derivative generation details ``` ### `media_collection_created` Path: ```text classes/event/media_collection_created.php ``` Triggered when a media collection is created. Required payload: ```text contextid courseid objectid = uckkarchive_media_collection.id userid other.collectionuuid other.collectiontype other.status other.visibility other.audiencesuitability ``` Associated revision: ```text uckkarchive_rev.revisiontype = media_collection_created ``` ### `media_exported` Path: ```text classes/event/media_exported.php ``` Triggered when one or more media objects are included in an export. Required payload: ```text contextid courseid objectid = uckkarchive_export.id userid other.exportuuid other.mediauuid other.exporttype other.redactionmode ``` For multi-media exports, the event may include count values but must not include a full media list when the list is sensitive. Safe count fields: ```text other.mediacount other.collectioncount other.markercount other.externalworkcount ``` --- ## 11. Content advisory events ### `content_marker_created` Path: ```text classes/event/content_marker_created.php ``` Triggered when a content advisory or cultural protocol marker is created. Required payload: ```text contextid courseid objectid = uckkarchive_content_marker.id userid other.markeruuid other.tagkey other.locator_type other.reviewstate other.visibility other.audiencesuitability ``` May include one target reference: ```text other.mediauuid other.itemuuid other.externalworkuuid ``` Must not include: ```text advisorytext when restricted cultural protocol note review note full locator text if it exposes sensitive content external source private URL ``` Associated revision: ```text uckkarchive_rev.revisiontype = content_marker_created ``` ### `content_marker_reviewed` Path: ```text classes/event/content_marker_reviewed.php ``` Triggered when a human reviewer changes advisory/cultural review state. Required payload: ```text contextid courseid objectid = uckkarchive_content_review.id userid = reviewer other.markeruuid other.reviewuuid other.previousreviewstate other.newreviewstate other.decision other.visibility other.audiencesuitability ``` Associated records: ```text uckkarchive_content_review uckkarchive_rev.revisiontype = content_marker_reviewed ``` Review rule: ```text AI may suggest tags or markers. Human review is required before advisory status becomes approved. Cultural protocol review cannot be replaced by AI. ``` --- ## 12. External work events ### `external_work_created` Path: ```text classes/event/external_work_created.php ``` Triggered when an external/foreign work reference is created. Required payload: ```text contextid courseid objectid = uckkarchive_external_work.id userid other.externalworkuuid other.worktype other.sourceownership other.visibility other.audiencesuitability ``` Must not imply ownership over third-party work. Must not include: ```text full copyrighted content private acquisition notes restricted source URL confidential review notes ``` Associated revision: ```text uckkarchive_rev.revisiontype = external_work_created ``` --- ## 13. Event-to-table mapping | Event | Primary table | Revision table? | Additional audit table | |---|---|---:|---| | `archive_viewed` | `uckkarchive` | No | Moodle log only | | `archive_item_created` | `uckkarchive_item` | Yes | `uckkarchive_prov` when applicable | | `archive_item_validated` | `uckkarchive_item` | Yes | `uckkarchive_prov` when applicable | | `archive_item_revised` | `uckkarchive_item` | Yes | — | | `archive_item_exported` | `uckkarchive_export` | Yes | export manifest | | `media_created` | `uckkarchive_media` | Yes | `uckkarchive_media_source` when applicable | | `media_updated` | `uckkarchive_media` | Yes | — | | `media_version_created` | `uckkarchive_media_version` | Yes | Moodle File API | | `media_collection_created` | `uckkarchive_media_collection` | Yes | — | | `media_exported` | `uckkarchive_export` | Yes | export manifest | | `content_marker_created` | `uckkarchive_content_marker` | Yes | — | | `content_marker_reviewed` | `uckkarchive_content_review` | Yes | `uckkarchive_content_review` | | `external_work_created` | `uckkarchive_external_work` | Yes | `uckkarchive_media_source` when applicable | --- ## 14. Event trigger points Events are triggered by server-side code only. Allowed trigger locations: ```text classes/local/* classes/external/* root controllers after successful state change scheduled tasks after successful state change restore code only when restore creates meaningful domain records and Moodle event policy allows it ``` Forbidden trigger locations: ```text templates AMD JavaScript CSS language files client-side-only handlers ``` Rule: ```text Client-side UI may request an action. Server-side code performs the action. Server-side code triggers the event. ``` --- ## 15. External service event behavior External services must trigger the same events as page controllers when they produce the same successful state change. Examples: ```text classes/external/add_media.php -> media_created classes/external/update_media.php -> media_updated classes/external/add_media_version.php -> media_version_created classes/external/add_content_marker.php -> content_marker_created classes/external/review_content_marker.php -> content_marker_reviewed classes/external/add_external_work.php -> external_work_created classes/external/export_media.php -> media_exported classes/external/export_items.php -> archive_item_exported ``` Rule: ```text The audit trail must not depend on whether the action came from UI, AJAX, service, task, or controller. ``` --- ## 16. Observer architecture Observer registration lives in: ```text db/events.php ``` Observer methods live in: ```text classes/observer.php ``` Observer methods may: ```text schedule derivative generation schedule thumbnail generation schedule export processing schedule search index rebuild invalidate render caches enqueue notification tasks update safe aggregate counters ``` Observer methods must not: ```text grant access validate records override policy reveal restricted data perform long blocking work copy restricted content to public areas create external authority records ``` Observer rule: ```text Observers react to events. Observers do not become the authority layer. ``` --- ## 17. Scheduled task interaction Events may cause scheduled work. Relevant tasks: ```text classes/task/generate_archive_exports.php classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/purge_expired_exports.php classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php classes/task/validate_pending_items.php ``` Task audit rule: ```text Scheduled tasks must produce audit records when they create or modify domain state. Scheduled tasks must not produce duplicate audit records when they only rebuild derived caches. ``` Examples: | Task action | Event required? | |---|---:| | Generate thumbnail version | Yes, `media_version_created` | | Generate preview derivative | Yes, `media_version_created` | | Rebuild search index only | No | | Purge expired export package | Yes, if export state changes to `purged` | | Mark export failed | Yes, export revision/event if implemented | | Rebuild content marker index only | No | --- ## 18. Revision audit model Revision records are stored in: ```text uckkarchive_rev ``` Revision records are required for meaningful changes to: ```text archive item content archive item status archive item visibility validation state restricted state media metadata media status media visibility media source media version collection membership content marker content advisory review state cultural protocol state external work metadata export status redaction state retention class ``` Revision records must include: ```text archiveid target object reference revisiontype versionno when applicable reason actor timestamp safe before/after summary when appropriate ``` Revision records must not store unredacted sensitive data in `beforejson` or `afterjson`. --- ## 19. Provenance audit model Provenance records are stored in: ```text uckkarchive_prov ``` Provenance records are required when an object is: ```text created from human input imported generated by system AI-assisted copied from another archive linked to external work derived from media associated with Assembly material associated with challenge material associated with integrity material ``` Provenance events and revision events may reference provenance IDs but must not duplicate the full provenance statement when it is sensitive. --- ## 20. Content advisory audit model Content advisory audit must track: ```text who created the marker who reviewed the marker which tag was applied which tag set was used which work/media/item/location was marked which review state was assigned which suitability value was assigned whether cultural restriction applies whether access requires context or review ``` Content advisory audit must not expose: ```text restricted cultural notes confidential review notes unredacted trauma descriptions private teaching notes private URLs full copyrighted excerpts ``` Rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 21. Cultural protocol audit model Cultural protocol audit applies to tags and markers such as: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Cultural protocol events must be especially minimal. Allowed event payload: ```text marker id marker uuid tag key review state visibility audience suitability object id context id ``` Forbidden event payload: ```text private protocol explanation names of community authorities unless already public and authorized restricted knowledge detail ceremonial detail sacred content description ``` --- ## 22. External/foreign media audit model External/foreign media audit applies to: ```text films books articles podcasts websites external videos external images public archive items third-party PDFs other external works ``` Audit must record: ```text external work creation external work metadata updates media source creation media source updates content markers attached to external works review decisions for external works exports that include external work references ``` Audit must not imply: ```text UCKK owns the external work UCKK has copied the external work UCKK has permission beyond recorded rights/source fields ``` --- ## 23. Export audit model Exports are audited through: ```text uckkarchive_export Moodle event classes uckkarchive_rev manifest.json ``` Export audit must record: ```text export requester export type export scope export redaction mode export status export timestamp included archive item UUIDs included media UUIDs included media version UUIDs included external work UUIDs included content marker UUIDs manifest hash when available expiry timestamp purge timestamp when applicable ``` Export events must not include full manifest JSON. Export package files use Moodle File API areas: ```text export_package export_manifest ``` --- ## 24. File access audit File access is governed through: ```text mod_uckkarchive_pluginfile() classes/local/file_area_registry.php classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php ``` File access checks must consider: ```text context capability file area itemid mediaid media version id content marker restrictions visibility media status archive item status validation state redaction state retention state audience suitability restricted cultural state restricted integrity state ``` File access events should not expose raw file details when files are restricted. --- ## 25. Event payload patterns ### Safe `other` payload pattern for archive items ```php [ 'archiveid' => $archiveid, 'archiveuuid' => $archiveuuid, 'itemuuid' => $itemuuid, 'itemtype' => $itemtype, 'status' => $status, 'visibility' => $visibility, 'validationstate' => $validationstate, ] ``` ### Safe `other` payload pattern for media ```php [ 'archiveid' => $archiveid, 'mediauuid' => $mediauuid, 'mediatype' => $mediatype, 'status' => $status, 'visibility' => $visibility, 'audiencesuitability' => $audiencesuitability, ] ``` ### Safe `other` payload pattern for media versions ```php [ 'archiveid' => $archiveid, 'mediauuid' => $mediauuid, 'mediaversionuuid' => $mediaversionuuid, 'versionno' => $versionno, 'versiontype' => $versiontype, 'filearea' => $filearea, ] ``` ### Safe `other` payload pattern for content markers ```php [ 'archiveid' => $archiveid, 'markeruuid' => $markeruuid, 'tagkey' => $tagkey, 'locator_type' => $locatortype, 'reviewstate' => $reviewstate, 'visibility' => $visibility, 'audiencesuitability' => $audiencesuitability, ] ``` ### Safe `other` payload pattern for external works ```php [ 'archiveid' => $archiveid, 'externalworkuuid' => $externalworkuuid, 'worktype' => $worktype, 'sourceownership' => $sourceownership, 'visibility' => $visibility, 'audiencesuitability' => $audiencesuitability, ] ``` --- ## 26. Redaction and restricted audit When an object is restricted, redacted, culturally restricted, or integrity restricted, the event still records that an action happened. The event must not reveal restricted detail. Safe restricted values: ```text restricted = true restrictedtype = restricted_cultural restrictedtype = restricted_integrity redactionstate = partial redactionstate = full ``` Unsafe restricted values: ```text full explanation of the restricted material sensitive evidence content private cultural protocol details trauma description confidential notes hidden external source ``` --- ## 27. Event URLs `get_url()` should point to the safest relevant UI page. Examples: | Event | URL target | |---|---| | `archive_viewed` | `view.php?id={cmid}` | | `archive_item_created` | `item.php?id={cmid}&itemid={itemid}` | | `archive_item_validated` | `validate.php?id={cmid}&itemid={itemid}` | | `archive_item_revised` | `item.php?id={cmid}&itemid={itemid}` | | `archive_item_exported` | `export.php?id={cmid}&exportid={exportid}` | | `media_created` | `media.php?id={cmid}&mediaid={mediaid}` | | `media_updated` | `media.php?id={cmid}&mediaid={mediaid}` | | `media_version_created` | `media.php?id={cmid}&mediaid={mediaid}` | | `media_collection_created` | `media.php?id={cmid}&collectionid={collectionid}` | | `media_exported` | `export.php?id={cmid}&exportid={exportid}` | URL access must still be checked by the destination controller. --- ## 28. Object mapping Each event class must define restore mappings. Examples: ```text archive_item_created -> uckkarchive_item archive_item_validated -> uckkarchive_item archive_item_revised -> uckkarchive_item archive_item_exported -> uckkarchive_export media_created -> uckkarchive_media media_updated -> uckkarchive_media media_version_created -> uckkarchive_media_version media_collection_created -> uckkarchive_media_collection media_exported -> uckkarchive_export content_marker_created -> uckkarchive_content_marker content_marker_reviewed -> uckkarchive_content_review external_work_created -> uckkarchive_external_work ``` `get_objectid_mapping()` must return the matching table name where Moodle supports mapping. `get_other_mapping()` must map IDs stored in `other` only when they are local database IDs. UUIDs in `other` do not require Moodle restore ID mapping. --- ## 29. Backup and restore interaction Backup and restore must preserve: ```text events only through Moodle log policy where applicable domain revision records provenance records content review records export records media version records relation records external work records ``` Restore must not replay events as if users performed new actions unless Moodle restore behavior explicitly requires new restore-time events. Restore must preserve data audit. Restore must not create false human validation events. Restore must not create false content review events. --- ## 30. Privacy API interaction Privacy provider must account for user links in: ```text events through Moodle log system uckkarchive_rev.createdby uckkarchive_prov.actorid uckkarchive_export.userid uckkarchive_content_review.reviewedby createdby fields modifiedby fields validatedby fields reviewedby fields ``` Privacy export must distinguish: ```text user-authored content user action metadata system logs third-party external work metadata restricted cultural protocol data restricted integrity data ``` Privacy deletion/anonymisation must not destroy institutional audit records when retention requires preservation, but must redact/anonymise personal fields according to policy. --- ## 31. Language strings Each event requires English and French language strings in: ```text lang/en/uckkarchive.php lang/fr/uckkarchive.php ``` Required string keys follow this pattern: ```text eventarchiveviewed eventarchiveitemcreated eventarchiveitemvalidated eventarchiveitemrevised eventarchiveitemexported eventmediacreated eventmediaupdated eventmediaversioncreated eventmediacollectioncreated eventmediaexported eventcontentmarkercreated eventcontentmarkerreviewed eventexternalworkcreated ``` Language strings must not expose sensitive details. --- ## 32. Event testing Tests must cover: ```text event class creation required payload fields safe payload behavior context assignment objectid assignment URL generation object mapping event trigger on successful action no event trigger on failed permission check revision record creation content review event behavior restricted/cultural payload redaction external work event behavior export event behavior ``` Required test files: ```text tests/archive_test.php tests/media_library_test.php tests/content_advisory_test.php tests/external_work_test.php tests/export_test.php tests/privacy_provider_test.php tests/services_test.php ``` Required Behat files: ```text tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` --- ## 33. Event implementation checklist for code generation Every event class must include: ```text namespace mod_uckkarchive\event defined('MOODLE_INTERNAL') || die() class extends \core\event\base protected function init() public static function get_name() public function get_description() public function get_url() public static function get_objectid_mapping() public static function get_other_mapping() protected function validate_data() ``` Every trigger call must provide: ```text context objectid userid courseid when applicable relateduserid when applicable other safe payload ``` Every trigger call must occur after: ```text capability check policy check database write file write when applicable revision record creation when applicable ``` --- ## 34. Forbidden event behavior The implementation must not: ```text trigger events from templates trigger events from AMD JavaScript trigger events before state changes succeed store full content in event other payload store raw file content in event other payload store private cultural protocol notes in event other payload store private review notes in event other payload store full manifest JSON in event other payload use events as permission checks use observers as authority layers create false validation events during restore create false review events during restore ``` --- ## 35. Final event and audit rule ```text mod_uckkarchive events make actions visible to Moodle. mod_uckkarchive revisions make domain change history durable. mod_uckkarchive provenance explains origin. mod_uckkarchive content reviews preserve human advisory decisions. mod_uckkarchive export records preserve package history. Events identify safe facts about successful actions. Events do not reveal restricted content. Events do not replace policy. Events do not replace revisions. Events do not replace provenance. Events do not transfer authority to or from external plugins. This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ``` ================================================================================================ FILE: mod/uckkarchive/docs/15_ui_templates_and_amd.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: da6b04ee0984a9f430e24528f2adccfd31ddb153b894cd0e4eb5e44b1279ec35 CONTENT_BYTES: 26730 ================================================================================================ # 15 — UI, Templates and AMD **Path:** `docs/15_ui_templates_and_amd.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** User interface, Mustache templates, output classes, Moodle renderer, AMD modules, and client-side behavior for the self-contained UCKK Archive, Media Library, and Content Advisory subsystem. --- ## 1. Purpose This document defines the final UI architecture for `mod_uckkarchive`. The UI must support: ```text archive browsing archive item cards archive item detail views media library browsing media upload and edit workflows media cards media collections media version lists media relation lists content advisory panels cultural protocol indicators external work cards proof cards Kristal cards provenance panels validation panels export previews restricted access messaging ``` The UI is Moodle-native and uses: ```text PHP output classes Moodle renderer Mustache templates AMD JavaScript modules external services Moodle language strings Moodle capabilities and context-aware policy filtering ``` The UI must never be the authority layer. --- ## 2. Core UI decision Canonical rule: ```text Server-side policy decides what data exists in the render payload. Templates render only. AMD modules enhance interaction only. ``` The UI may: ```text display archive/media data display policy-filtered actions display content advisories display cultural protocol notices display external work metadata refresh cards through AJAX submit forms open panels filter lists request export previews show upload progress show media version lists show collection membership ``` The UI must not: ```text authorize access decide restricted visibility decide cultural protocol access decide validation authority decide export authority reconstruct hidden data expose hidden metadata in the DOM store policy-sensitive state in JavaScript trust client-side filtering for security ``` --- ## 3. UI architecture layers The UI architecture has five layers: ```text controller output class renderer template AMD module ``` Layer responsibilities: | Layer | Responsibility | |---|---| | Controller | Resolve context, require login, call domain/service logic, pass renderable objects to output. | | Output class | Build permission-filtered render payloads. | | Renderer | Connect output classes to Moodle page rendering and Mustache templates. | | Template | Display already-filtered data. | | AMD module | Add client-side behavior and call external services. | Authority rule: ```text Policy belongs in classes/local. Renderable filtering belongs in classes/output. Templates and AMD modules are not authority layers. ``` --- ## 4. Required output classes Required output classes: ```text classes/output/archive_item_card.php classes/output/archive_view.php classes/output/content_advisory_panel.php classes/output/external_work_card.php classes/output/kristal_card.php classes/output/media_card.php classes/output/media_collection.php classes/output/media_library.php classes/output/media_version_list.php classes/output/provenance_panel.php classes/output/renderer.php ``` Optional but recommended output classes: ```text classes/output/export_preview.php classes/output/media_relation_list.php classes/output/restricted_notice.php classes/output/validation_panel.php ``` Output class rule: ```text Output classes prepare display data only after policy checks have been applied. ``` Output classes must not expose: ```text raw restricted metadata hidden cultural protocol notes private review notes unfiltered file URLs unfiltered external service parameters unredacted personal data unapproved content marker details hidden integrity-related metadata ``` --- ## 5. Renderer Canonical renderer: ```text classes/output/renderer.php ``` The renderer owns the connection between output classes and templates. Renderer methods should include: ```text render_archive_view render_archive_item_card render_media_library render_media_card render_media_collection render_media_version_list render_content_advisory_panel render_external_work_card render_kristal_card render_provenance_panel render_validation_panel render_export_preview ``` Renderer rule: ```text The renderer formats renderable objects. The renderer does not perform final access decisions. ``` --- ## 6. Required templates Required Mustache templates: ```text templates/archive_item_card.mustache templates/archive_view.mustache templates/content_advisory_panel.mustache templates/external_work_card.mustache templates/kristal_card.mustache templates/media_card.mustache templates/media_collection.mustache templates/media_library.mustache templates/media_relation_list.mustache templates/media_upload.mustache templates/media_version_list.mustache templates/proof_card.mustache templates/provenance_panel.mustache templates/validation_panel.mustache ``` Optional but recommended templates: ```text templates/export_preview.mustache templates/restricted_notice.mustache templates/empty_state.mustache templates/filter_bar.mustache templates/action_menu.mustache ``` Template rule: ```text Templates render pre-filtered data. Templates do not enforce access. Templates do not contain hidden restricted data for later client-side display. ``` --- ## 7. Required AMD source modules Required AMD source files: ```text amd/src/archive.js amd/src/content_advisory.js amd/src/export.js amd/src/external_work.js amd/src/kristal.js amd/src/media.js amd/src/media_collection.js ``` Required AMD build files: ```text amd/build/archive.min.js amd/build/content_advisory.min.js amd/build/export.min.js amd/build/external_work.min.js amd/build/kristal.min.js amd/build/media.min.js amd/build/media_collection.min.js ``` AMD build rule: ```text amd/src is source. amd/build is generated. Generated AMD build files are not edited by hand. ``` AMD security rule: ```text AMD modules do not authorize access. AMD modules do not reveal restricted data. AMD modules do not infer permissions. AMD modules call external services that re-check all policy server-side. ``` --- ## 8. Page controllers using UI components Main UI controllers: ```text view.php item.php media.php add.php validate.php export.php index.php ``` Controller roles: | Controller | UI role | |---|---| | `view.php` | Main activity view: archive dashboard, media entry points, primary navigation. | | `item.php` | Archive item detail view. | | `media.php` | Media library view. | | `add.php` | Archive item/media creation controller. | | `validate.php` | Validation and review controller. | | `export.php` | Export preview and export request controller. | | `index.php` | Course-level list of UCKK Archive activities. | Controller rule: ```text Controllers coordinate request flow. Controllers do not contain duplicated rendering or authorization logic. ``` --- ## 9. Archive view UI The archive view displays: ```text activity title intro archive summary archive filters archive item list media library entry point collections entry point validation queue entry point export entry point restricted access indicators ``` Required output/template pair: ```text classes/output/archive_view.php templates/archive_view.mustache ``` Required AMD module: ```text amd/src/archive.js ``` Archive view rules: ```text Only visible archive items are included in the render payload. Restricted item counts must not leak details to unauthorized users. Actions are shown only when the user can perform them. ``` --- ## 10. Archive item card UI Archive item cards display policy-filtered summary data. Required output/template pair: ```text classes/output/archive_item_card.php templates/archive_item_card.mustache ``` Archive item card may display: ```text title summary type status visibility validation state provenance indicator media count proof count content advisory indicator restricted indicator last modified date available actions ``` Archive item card must not display: ```text hidden restricted notes private validation notes integrity-only details unapproved cultural protocol notes unfiltered file URLs ``` --- ## 11. Media library UI The media library UI is the main interface for managed media objects. Required output/template pair: ```text classes/output/media_library.php templates/media_library.mustache ``` Required AMD module: ```text amd/src/media.js ``` The media library must support: ```text media search media filtering media cards media upload entry media edit entry media collection browsing media version access media relation access content advisory indicators external work indicators source and rights indicators restricted state labels audience suitability labels ``` Media library filters should include: ```text media type status visibility collection tag content advisory tag audience suitability source kind external work language rights/license provenance creator date ``` Media library rule: ```text Search and filter results are server-filtered before display. Client-side filters only refine already-permitted result sets. ``` --- ## 12. Media card UI Media cards display a policy-filtered summary of a media object. Required output/template pair: ```text classes/output/media_card.php templates/media_card.mustache ``` Media cards may display: ```text thumbnail title media type status visibility audience suitability source kind license/rights summary version label content advisory indicator cultural protocol indicator collection membership available actions ``` Media cards must not display: ```text restricted thumbnails to unauthorized users hidden cultural protocol notes private content review notes unapproved advisory details original download links unless authorized raw file identifiers as authority ``` Media card action examples: ```text view edit download add version add to collection view versions view relations view advisories export delete soft ``` Actions are present only when policy allows them. --- ## 13. Media upload UI Required template: ```text templates/media_upload.mustache ``` Required AMD module: ```text amd/src/media.js ``` Upload UI must collect: ```text title description media type source kind ownership kind license/rights statement visibility audience suitability initial file caption/transcript files when relevant collection assignment content advisory draft markers when relevant ``` Upload UI must respect: ```text Moodle File API draft areas configured file limits allowed MIME types media policy content advisory policy external work rules cultural protocol rules ``` Upload UI rule: ```text Client-side validation improves usability only. Server-side validation is mandatory. ``` --- ## 14. Media collection UI Required output/template pair: ```text classes/output/media_collection.php templates/media_collection.mustache ``` Required AMD module: ```text amd/src/media_collection.js ``` Media collection UI must support: ```text collection list collection detail view media membership sort order membership roles add media to collection remove media from collection collection visibility collection audience suitability collection export ``` Collection UI rule: ```text A collection does not own media. A collection displays only media objects the user can access. ``` --- ## 15. Media version list UI Required output/template pair: ```text classes/output/media_version_list.php templates/media_version_list.mustache ``` Media version UI must show: ```text version number version label created date created by reason change summary file type file size hash indicator status available actions ``` Media version UI must hide: ```text restricted files restricted version notes download links for unauthorized users file areas unavailable to the current user ``` Version action examples: ```text view download compare metadata restore as current archive version ``` Version UI rule: ```text Version visibility is policy-filtered independently from the parent media object. ``` --- ## 16. Media relation list UI Required template: ```text templates/media_relation_list.mustache ``` Optional output class: ```text classes/output/media_relation_list.php ``` Relation UI must support: ```text source relation target relation relation type direction related object label related object type available actions ``` Relation types include: ```text belongs_to_item belongs_to_kristal belongs_to_collection is_derivative_of is_translation_of is_excerpt_of is_proof_for is_source_for replaces references duplicates references_external_work contains_content_marker ``` Relation UI rule: ```text Relations to inaccessible targets must be hidden or shown only as redacted placeholders. ``` --- ## 17. Content advisory panel UI Required output/template pair: ```text classes/output/content_advisory_panel.php templates/content_advisory_panel.mustache ``` Required AMD module: ```text amd/src/content_advisory.js ``` The content advisory panel must support: ```text content advisory tags cultural protocol tags audience suitability severity locator display review state review notes when authorized context notes restricted state available actions ``` Canonical user-facing labels: ```text Content advisory Content warning Cultural advisory Cultural protocol Audience suitability ``` Avoid system-facing use of `trigger` as the primary term. Allowed user-facing phrase: ```text Trigger warning ``` Content advisory UI rule: ```text A content advisory does not ban media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 18. Content marker locator UI Content marker UI must support these locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Examples displayed by the UI: ```text 01:12:30-01:15:10 page 42-45 chapter 3 section 2.4 #section-3 manual note ``` Locator UI rule: ```text Locators must be useful without storing unauthorized copies of external content. ``` --- ## 19. Content review UI Required form/output components: ```text classes/form/content_review_form.php classes/output/content_advisory_panel.php templates/content_advisory_panel.mustache amd/src/content_advisory.js ``` Content review UI must support review states: ```text draft pending_review reviewed approved contested retired ``` Content review UI must support decisions such as: ```text approve advisory request changes mark contested retire marker adjust severity adjust audience suitability add context note require cultural permission ``` Content review UI rule: ```text AI may suggest tags or markers. Human review is required before advisory state becomes approved. Cultural protocol access cannot be approved by AI. ``` --- ## 20. External work UI Required output/template pair: ```text classes/output/external_work_card.php templates/external_work_card.mustache ``` Required AMD module: ```text amd/src/external_work.js ``` External work UI must display: ```text title work type creator publisher publication year citation identifier URL when allowed rights statement license summary content advisory count available actions ``` External work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External work UI rule: ```text The module may reference foreign media without copying it. The UI must not imply UCKK ownership over third-party works. ``` --- ## 21. Provenance panel UI Required output/template pair: ```text classes/output/provenance_panel.php templates/provenance_panel.mustache ``` The provenance panel may display: ```text origin source component source identifier created by modified by validation actor file hash manifest reference import metadata AI-assistance indicator external work reference content review reference ``` Provenance values: ```text human ai_assisted imported system archive assembly challenge integrity media external_work content_review ``` Provenance UI rule: ```text Provenance explains origin. Provenance does not grant authority. ``` --- ## 22. Validation panel UI Required template: ```text templates/validation_panel.mustache ``` Optional output class: ```text classes/output/validation_panel.php ``` Validation panel must support: ```text validation state review summary contestation state revision link restricted state available validation actions ``` Validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Validation UI rule: ```text Validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. ``` --- ## 23. Kristal card UI Required output/template pair: ```text classes/output/kristal_card.php templates/kristal_card.mustache ``` Required AMD module: ```text amd/src/kristal.js ``` Kristal UI may display: ```text title summary source items linked media proof indicators provenance indicators validation state restricted state available actions ``` Kristal UI rule: ```text Kristal display must not bypass archive, media, proof, or content advisory policy. ``` --- ## 24. Proof card UI Required template: ```text templates/proof_card.mustache ``` Proof card may display: ```text proof title proof type summary linked archive item linked media validation state provenance state restricted state available actions ``` Proof UI rule: ```text Proof data is filtered by archive policy and media policy before rendering. ``` --- ## 25. Export preview UI Required AMD module: ```text amd/src/export.js ``` Optional template/output pair: ```text classes/output/export_preview.php templates/export_preview.mustache ``` Export preview must show: ```text selected archive items selected media selected media versions collections content markers external work references file count manifest inclusion redaction level restricted exclusions cultural protocol exclusions estimated package scope ``` Export preview rule: ```text Export preview must reflect actual server-side export authority. It must not list hidden items as detailed exclusions for unauthorized users. ``` --- ## 26. Restricted notice UI Optional template/output pair: ```text classes/output/restricted_notice.php templates/restricted_notice.mustache ``` Restricted notices may appear for: ```text restricted media restricted archive item restricted cultural material restricted integrity material unapproved content advisory details hidden external work references missing permission retention-limited records ``` Restricted notice rule: ```text A restricted notice may explain that access is limited. It must not reveal the protected content itself. ``` --- ## 27. Language strings Language files: ```text lang/en/uckkarchive.php lang/fr/uckkarchive.php ``` UI strings must cover: ```text archive labels media labels collection labels relation labels version labels content advisory labels cultural protocol labels external work labels source/rights labels validation labels restricted notices export labels empty states form labels error messages capability names ``` Language rule: ```text Every public UI string has matching English and French keys. Templates and AMD modules use language strings, not hard-coded display text. ``` --- ## 28. Accessibility UI must support: ```text keyboard navigation semantic headings ARIA labels where needed accessible form labels visible focus state screen-reader-friendly advisory labels non-color-only restricted indicators caption/transcript display where available clear error messages ``` Accessibility rule: ```text Content advisory and cultural protocol warnings must be understandable without relying only on color, icon, or hover text. ``` --- ## 29. Responsive design The UI must support: ```text desktop tablet mobile narrow Moodle content regions drawer navigation course format constraints ``` Responsive behavior: ```text cards stack on narrow screens filters collapse into panels action menus remain keyboard accessible tables become cards or scrollable regions media previews fit the available region ``` --- ## 30. Empty states Empty states should exist for: ```text no archive items no media no collections no versions no relations no content markers no external works no search results no exportable items restricted/no access ``` Empty state rule: ```text Empty states must not reveal that hidden restricted records exist unless the user is authorized to know that. ``` --- ## 31. Error states UI error states should handle: ```text permission denied service failure invalid sesskey invalid context missing media missing archive item missing external work restricted media restricted cultural protocol unsupported file type upload failure export failure validation failure ``` Error state rule: ```text Error messages must be useful but must not leak restricted metadata. ``` --- ## 32. Loading states AMD modules should support loading states for: ```text card refresh search filter change media upload collection update version list load content marker load export preview export status ``` Loading state rule: ```text Loading states improve usability only. They do not cache protected data beyond the current authorized request. ``` --- ## 33. Client-side service calls AMD modules may call external services declared in: ```text db/services.php ``` Service calls must include: ```text context id course module id when needed record id or uuid sesskey through Moodle request handling operation-specific parameters ``` Service call rule: ```text Every external service re-checks context, capability, policy, visibility, lifecycle state, and redaction server-side. ``` --- ## 34. Data attributes Templates may include safe data attributes such as: ```text data-region data-action data-media-id data-media-uuid data-item-id data-collection-id data-external-work-id ``` Templates must not include unsafe data attributes such as: ```text hidden restricted notes raw file paths unredacted private metadata unapproved cultural protocol notes server-only capability assumptions secret tokens outside Moodle request patterns ``` Data attribute rule: ```text DOM data is not private storage. Anything rendered to the DOM is considered visible to the current user. ``` --- ## 35. File preview UI File preview UI may display: ```text thumbnail preview image media player transcript link caption availability document preview link download action when authorized ``` File preview UI must respect: ```text media policy file area permissions restricted state content advisory policy cultural protocol restrictions Moodle pluginfile access checks ``` Preview rule: ```text Preview access and original download access are separate decisions. ``` --- ## 36. Content advisory display patterns Content advisory display may include: ```text small indicator on cards full advisory panel on detail pages warning banner before viewing media context note before playback locator list for specific scenes/pages restricted cultural protocol notice review state indicator for staff ``` Display rule: ```text The UI should warn responsibly without unnecessarily exposing sensitive details to audiences that should not see them. ``` --- ## 37. Cultural protocol UI Cultural protocol UI may include: ```text restricted cultural indicator requires context label requires permission label not for public export label elder review required label community permission required label seasonal/contextual access label ``` Cultural protocol UI rule: ```text Cultural protocol details are themselves potentially sensitive. The UI must distinguish between public-facing notices and restricted protocol notes. ``` --- ## 38. External work locator UI External work locator UI may display: ```text film timestamp book page range article section website fragment manual reference citation ``` Examples: ```text Movie Maïna — content advisory — 01:12:30-01:15:10 Book The Body Keeps the Score — content advisory — page 42-45 ``` External work locator rule: ```text Locators identify where advisory-relevant content occurs. Locators do not require storing or copying the external work. ``` --- ## 39. Privacy-aware UI Privacy-aware UI must: ```text hide personal metadata unless authorized redact reviewer notes when required avoid exposing user IDs unnecessarily avoid exposing private source metadata filter content review history respect privacy provider rules ``` Privacy UI rule: ```text If data would not be available through a permitted server response, it must not appear in UI payloads, templates, or JavaScript. ``` --- ## 40. Backup/restore-aware UI UI labels and admin screens should make clear that the module owns: ```text archive records media records media versions collections relations tags content markers content reviews external work references export manifests ``` Backup/restore UI rule: ```text Restored media remains subject to restored visibility, restricted state, content advisory policy, and cultural protocol rules. ``` --- ## 41. Testing requirements UI and AMD tests must cover: ```text archive view rendering archive item card rendering media library rendering media card rendering media upload UI media collection UI media version list UI media relation list UI content advisory panel UI content marker locator UI content review UI external work card UI restricted notice UI export preview UI language string coverage permission-filtered actions restricted data not rendered cultural protocol data not leaked AJAX service error handling ``` Required Behat files: ```text tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` Testing rule: ```text Tests verify final target behavior, not historical transitions. ``` --- ## 42. Final rule The UI is a Moodle-native presentation and interaction layer for a self-contained archive, media library, and content advisory system. The UI must render only policy-filtered data, call server-side services for state changes, and avoid leaking restricted archive, media, cultural protocol, content review, or external work metadata. This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/16_integration_with_courses.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 06dded72508521f5a977fcea53dfa33dff3aa7d102a532cc9c2780a5d15438e8 CONTENT_BYTES: 27817 ================================================================================================ # 16 — Integration with Courses **Path:** `docs/16_integration_with_courses.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Course-level integration for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Purpose This document defines how `mod_uckkarchive` integrates with Moodle courses. `mod_uckkarchive` is a Moodle activity module. It exists inside a Moodle course as a course module instance. The module provides a self-contained archive, media library, and content advisory system while respecting Moodle’s course, context, visibility, role, group, completion, backup, restore, and privacy systems. Canonical formula: ```text Moodle course owns the course context. mod_uckkarchive owns archive/media/content-advisory records inside its activity context. Moodle gradebook owns grades. ``` --- ## 2. Course integration decision `mod_uckkarchive` integrates with courses as a normal Moodle activity module installed at: ```text mod/uckkarchive ``` Each activity instance is stored in: ```text uckkarchive ``` Each instance belongs to a Moodle course through Moodle’s standard course module system. The module must not create its own independent course system. The module must not bypass Moodle course visibility, role assignment, group restrictions, or activity availability. --- ## 3. Course-level responsibilities Moodle course responsibilities: ```text course identity course sections course visibility course enrolments course roles groups and groupings activity availability activity completion shell gradebook ownership course backup container course restore container course navigation ``` `mod_uckkarchive` responsibilities inside the course: ```text archive records media records media versions media collections media relations media tags content advisory tags content markers content reviews external work references proof records Kristals provenance revision history validation state restricted metadata export packages export manifests ``` --- ## 4. Course module context All instance-level access checks must resolve the Moodle context: ```text context_module ``` The context is resolved from: ```text course id course module id activity instance id ``` The central context resolver belongs in: ```text classes/local/context_resolver.php ``` Context resolver responsibilities: ```text load course load course module load uckkarchive instance validate component validate module type return context_module return course record return cm record return archive instance record ``` Controllers and services must not duplicate context resolution logic. --- ## 5. Required Moodle callbacks Course integration depends on Moodle module callbacks in: ```text lib.php ``` Required callback categories: ```text add instance update instance delete instance course module info navigation activity completion file serving backup support restore support view logging user outline where needed ``` The implementation must follow Moodle module conventions for `mod_uckkarchive`. --- ## 6. Activity instance record The `uckkarchive` table stores the activity instance. The activity instance must include fields for: ```text id course name intro introformat archive mode default visibility default media visibility default audience suitability default advisory behavior allow media library allow external work references allow content advisories allow exports enable group mode behavior completion settings timecreated timemodified ``` The `course` field links the activity instance to the Moodle course. The activity instance does not own enrolments. --- ## 7. Activity modes The module may support course-facing modes such as: ```text archive media_library archive_and_media restricted_archive teaching_collection evidence_archive portfolio_archive ``` Mode behavior controls defaults only. Mode behavior must not bypass capability checks. Mode behavior must not bypass content advisory policy. Mode behavior must not bypass cultural protocol restrictions. --- ## 8. Course section display `mod_uckkarchive` appears in Moodle course sections like any other activity. The activity page is served by: ```text view.php ``` Course-level listing is served by: ```text index.php ``` Archive item pages are served by: ```text item.php ``` Media library page is served by: ```text media.php ``` Export page is served by: ```text export.php ``` Validation page is served by: ```text validate.php ``` The controller must resolve the course module context before loading activity-owned records. --- ## 9. Course visibility Moodle controls whether the activity is visible in the course. `mod_uckkarchive` controls visibility of records inside the activity. Two visibility layers apply: ```text Moodle activity visibility archive/media record visibility ``` The activity must be visible to the user before activity records are shown. A visible activity does not automatically make all archive/media records visible. A hidden activity blocks ordinary access even when an internal archive/media item has public visibility. --- ## 10. Internal visibility values Internal visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Course integration primarily uses: ```text user group course restricted restricted_cultural restricted_integrity ``` The value `institutional` must normalize to: ```text institution ``` --- ## 11. Course visibility rule Course-level visibility rule: ```text User access requires Moodle course/module access first. Then mod_uckkarchive policy decides internal archive/media/content access. ``` Order of evaluation: ```text course exists course module exists module is mod_uckkarchive user can access course user can access activity activity availability permits access capability permits access archive/media/content policy permits access ``` --- ## 12. Enrolment boundary `mod_uckkarchive` does not own enrolments. The module must not: ```text enrol users unenrol users create cohorts assign course roles alter course membership ``` The module may read enrolment-derived access through Moodle APIs. The module may use Moodle capabilities assigned through course/module contexts. --- ## 13. Role and capability integration Course integration uses Moodle role assignments and capabilities. Archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Capability checks must use the resolved `context_module` unless a broader context is explicitly required by Moodle. --- ## 14. Add instance capability Adding an archive activity to a course requires: ```text mod/uckkarchive:addinstance ``` This capability is checked by Moodle when adding the activity to a course. Creating an activity instance does not automatically grant permission to validate, export, download originals, manage cultural protocols, or view restricted media. --- ## 15. View capability Viewing the activity shell requires: ```text mod/uckkarchive:view ``` Viewing internal media records may also require: ```text mod/uckkarchive:viewmedia ``` Viewing restricted media may require: ```text mod/uckkarchive:viewrestrictedmedia ``` Viewing culturally restricted records may require: ```text mod/uckkarchive:viewculturallyrestricted ``` Viewing the activity page does not imply full internal access. --- ## 16. Groups and groupings The module must respect Moodle group mode where the activity/course uses groups. Relevant group behaviors: ```text no groups separate groups visible groups grouping restriction ``` Group-aware archive/media rules apply to records with visibility: ```text group ``` Group-aware filtering must apply to: ```text archive item list media library list collections proof records Kristal records content markers external work teaching notes exports search results AJAX service responses ``` Group filtering must happen server-side. AMD modules may request group filters, but they must not enforce group authority. --- ## 17. Group ownership Archive and media records may store: ```text groupid ``` Group ownership means the record belongs to a group context inside the activity. Group ownership does not create a Moodle group. Group ownership does not override Moodle group mode. When group mode is separate groups, users must not see records belonging only to other groups unless they have the required Moodle permission to access all groups. --- ## 18. Course collections Media collections may be course-facing. Examples: ```text course media pack week module collection teaching collection challenge evidence collection Kristal source collection public summary collection restricted staff collection cultural protocol collection ``` Course-facing collections belong to `uckkarchive_media_collection`. A collection can include media from the same activity instance. Cross-activity reuse must be explicit and policy controlled. --- ## 19. Course archive items Course archive items may represent: ```text course work learning artifact portfolio item challenge evidence proof minutes decision snapshot Kristal source public summary restricted integrity summary external work teaching note ``` Course archive items belong to `uckkarchive_item`. Course archive items may link to media records, external works, content markers, and content advisories. --- ## 20. Course media library The media library is an internal module-owned subsystem. Course users may access media library features only when policy permits. Course media library features may include: ```text browse media upload media view media card view media preview download original create media version create collection tag media link media to archive item review content advisories reference external works ``` Each feature requires capability and policy checks. --- ## 21. Course content advisories Content advisories support responsible teaching and viewing inside courses. Content advisories can apply to: ```text archive items media objects media versions external works content markers collections public summaries exports ``` Course-facing advisory behavior may include: ```text show notice before viewing show cultural protocol note hide item from youth-facing view require guided access restrict public export require staff review require cultural access permission ``` Content advisory logic belongs in: ```text classes/local/content_policy.php ``` --- ## 22. External works in courses The module may reference external or foreign works used in teaching. External works are stored in: ```text uckkarchive_external_work ``` The module may store: ```text title creator publisher source type citation URL external identifier rights/license metadata content markers advisory tags review notes teaching notes audience suitability cultural protocol restrictions ``` The module must not imply UCKK ownership over third-party works. The module may store an external work file only when storage is permitted by policy, rights, or license. --- ## 23. Course examples Course examples: ```text A film shown in class has content markers with timecodes. A book used in a reading week has page-range advisories. A student-submitted media item has restricted cultural review notes. A teacher creates a course media pack for guided access. A staff member exports a validated proof bundle. A public summary excludes culturally restricted media. ``` These examples must be implemented through archive/media/content policy, not through template-only hiding. --- ## 24. Completion integration The module may support Moodle activity completion. Completion may be based on: ```text viewing the activity viewing required archive item submitting archive item uploading media creating proof reviewing advisory notice teacher validation manual completion ``` Completion logic belongs in: ```text classes/completion/custom_completion.php ``` Completion must not require: ```text viewing restricted content without permission downloading original restricted media viewing culturally restricted material reviewing integrity records without authority ``` Completion conditions must respect access rules. --- ## 25. Gradebook boundary `mod_uckkarchive` does not own grades. The module must not become the gradebook authority. The Moodle gradebook owns: ```text grade items grade values final grades grade aggregation grade export grade history ``` `mod_uckkarchive` may preserve: ```text graded artifact snapshot submission evidence teacher feedback archive validation notes course work media proof of completion exported archive package ``` Preserving grade-related evidence does not make the archive the gradebook. --- ## 26. Grade-related evidence If archive records reference graded work, they must store archive-owned metadata only. Allowed archive metadata: ```text source activity reference source course id source user id source timestamp submitted file copy where permitted provenance validation state teacher note copy where permitted export manifest reference ``` Forbidden behavior: ```text recalculate grade modify grade override gradebook replace Moodle assignment records own grade appeals ``` --- ## 27. Course navigation Course navigation may expose: ```text activity view archive item list media library collections exports validation tools restricted tools content advisory tools external works ``` Navigation entries must be capability-filtered. Restricted tools must not appear to users without authority. Navigation visibility is not authorization. The controller and service layer must still enforce access. --- ## 28. Course search Course search may include archive and media records when policy permits. Search results must respect: ```text course/module access visibility group mode media status archive item status content advisory policy cultural protocol restrictions restricted integrity policy redaction state deleted_soft state ``` Search must not leak restricted titles, private notes, cultural protocol notes, or third-party restricted metadata. --- ## 29. Course backup Course backup includes `mod_uckkarchive` activity instances and module-owned records. Backup must preserve: ```text activity instance archive items media records media versions media collections media relations media tags content advisory tags content tag sets content markers content reviews external works media source records proof records Kristals provenance revisions validation state exports files manifests ``` Backup must not create or own: ```text grades enrolments institutional registry authority challenge workflow authority assembly decision authority integrity case authority reporting authority ``` --- ## 30. Course restore Course restore must restore the activity inside the target course. Restore must remap: ```text course id course module id activity instance id user ids group ids archive item ids media ids media version ids collection ids relation ids content marker ids content review ids external work ids file itemids ``` Restore must preserve: ```text visibility restricted state cultural protocol restrictions content advisories redaction state validation state provenance revision history export manifest history ``` Restore must not make restricted course records public. --- ## 31. Course reset If Moodle course reset support is implemented, the module must provide explicit reset behavior. Possible reset options: ```text remove student draft archive items remove student media drafts remove course-generated exports keep validated archive records keep staff media library keep external work references keep content advisory vocabulary keep cultural protocol records ``` Course reset must not silently delete preserved evidence. Course reset must not delete culturally restricted records without explicit authority. Course reset must respect retention policy. --- ## 32. Calendar integration Calendar integration is optional and must remain limited. The module may create or expose dates such as: ```text archive submission due date validation deadline review deadline collection release date media availability date ``` Calendar events must not expose restricted titles, cultural protocol notes, or private advisory details to unauthorized users. The archive is not the course calendar authority. --- ## 33. Availability dates The module may support availability dates for archive/media records. Availability may include: ```text available from available until review window export window collection release window restricted staff window ``` Availability dates do not replace Moodle activity availability. The most restrictive applicable rule wins. --- ## 34. User data in courses Course users may contribute: ```text archive items media uploads proof records comments where implemented content advisory suggestions external work references review notes where permitted ``` User-linked data must be handled through: ```text classes/privacy/provider.php ``` Privacy behavior must respect both Moodle course context and archive/media preservation rules. --- ## 35. Teacher workflows Teachers may use course integration to: ```text create archive activity create course archive item upload teaching media create media collection reference external work add content advisory marker review content advisory suggestion publish course-facing media pack validate archive item export course archive package ``` Teacher authority depends on capabilities and policy. Teacher role alone is not hardcoded authority. --- ## 36. Student workflows Students may use course integration to: ```text view allowed archive items view allowed media submit archive item upload media where permitted view advisory notices submit content advisory suggestion where permitted access guided collections view feedback or validation status where permitted ``` Students must not access restricted staff records, restricted cultural records, private review notes, or integrity-restricted media unless explicit policy permits it. --- ## 37. Staff and reviewer workflows Staff/reviewers may: ```text validate archive items review media metadata review content advisories manage cultural protocol notes manage restricted records create export packages review external work references manage collections ``` Reviewer permissions are capability-based. The module must support review workflows without relying on hardcoded user IDs. --- ## 38. Public-facing course material Some archive/media material may be public-facing. Public-facing output must pass all checks: ```text activity permits access record visibility is public record status permits display content advisory policy permits display cultural protocol policy permits display redaction policy permits display rights/license permits display export/public summary policy permits display ``` Public-facing course material must not expose internal notes, private provenance details, cultural protocol notes, or restricted file URLs. --- ## 39. Public summaries Course archive items may include public summaries. Public summaries use file area: ```text item_publicsummary ``` Public summaries must be separately approved. Public summaries may differ from internal archive records. Public summaries must not automatically include original restricted media. --- ## 40. Activity deletion Deleting a course module instance triggers module deletion behavior. Deletion must respect: ```text Moodle deletion lifecycle privacy obligations retention obligations institutional memory rules cultural protocol restrictions export retention rules ``` The module must not leave orphaned active records. The module must not silently destroy preserved evidence that retention policy requires. Where Moodle requires deletion, the module must handle records according to defined retention/redaction policy. --- ## 41. Duplication inside a course Duplicating the activity inside a course must preserve internal structure only when Moodle duplication/backup rules permit it. Duplication must generate new local record IDs. Portable identity may preserve or fork UUIDs according to restore policy. Duplication must not: ```text make restricted media public copy disallowed third-party files drop content advisories drop cultural protocol restrictions drop source ownership metadata drop provenance ``` --- ## 42. Cross-course reuse Cross-course reuse is not implicit. A media object or collection used in another course must be: ```text copied through backup/restore exported/imported with manifest referenced through a controlled relation shared through a controlled institutional mechanism ``` Cross-course reuse must preserve: ```text source uuid rights metadata content advisories cultural protocol restrictions visibility redaction state provenance ``` --- ## 43. Course import Moodle course import may copy activity instances. Import must behave like controlled restore. Imported archive/media records must not lose: ```text file ownership content markers content reviews external work references media source records validation state restricted state cultural protocol restrictions ``` Course import must not import gradebook authority into the archive. --- ## 44. Course reporting boundary `mod_uckkarchive` may provide course-level archive views and export packages. `report_uckk` owns institutional reporting. The archive module may expose course activity data to reporting plugins through controlled APIs. The archive module must not become the institutional reporting authority. --- ## 45. Course export behavior Course-level archive exports may include: ```text selected archive items course media collections proof bundles validated items public summaries external work metadata content markers content advisory tags export manifests ``` Exports must exclude unauthorized restricted records. Exports must preserve content advisory and cultural protocol metadata where policy permits. Exports must not include third-party files unless rights and policy permit. --- ## 46. Events in course context Course integration must trigger Moodle events in the correct context. Examples: ```text archive_viewed archive_item_created archive_item_validated archive_item_revised archive_item_exported media_created media_updated media_version_created media_collection_created media_exported content_marker_created content_marker_reviewed external_work_created ``` Events must use `context_module`. Events must not expose restricted content in event data. --- ## 47. Course services External services used in course views must accept and validate: ```text course module id archive instance id record id or uuid context sesskey where required ``` Services must return permission-filtered data. Services must not return hidden records for client-side filtering. Services must not expose restricted records through autocomplete, search, preview, or card-render endpoints. --- ## 48. Course UI rendering Course UI rendering uses: ```text classes/output/archive_view.php classes/output/archive_item_card.php classes/output/media_library.php classes/output/media_card.php classes/output/media_collection.php classes/output/content_advisory_panel.php classes/output/external_work_card.php classes/output/renderer.php ``` Templates receive already-filtered render data. Templates must not make access decisions. AMD modules enhance UI behavior only. --- ## 49. Language strings Course-facing strings belong in: ```text lang/en/uckkarchive.php lang/fr/uckkarchive.php ``` Strings must cover: ```text activity names course view labels archive actions media actions collection actions content advisory notices cultural protocol notices external work labels completion descriptions capability names error messages privacy descriptions backup/restore descriptions ``` English and French keys should remain aligned. --- ## 50. Installation defaults New activity instances should define safe defaults. Recommended safe defaults: ```text default visibility = course default media visibility = course default audience suitability = guided allow media library = enabled allow external work references = enabled allow content advisories = enabled allow public summaries = disabled unless configured allow exports = capability-controlled restricted cultural access = disabled by default for ordinary roles restricted integrity access = disabled by default for ordinary roles ``` Safe defaults may be changed by site/admin settings and activity settings. --- ## 51. Settings hierarchy Settings may exist at: ```text site plugin settings activity instance settings record-level settings media-level settings content advisory settings ``` The most restrictive applicable rule wins. Activity settings must not override site-level restrictions. Record-level settings must not bypass capability or policy checks. --- ## 52. Course integration files Files that implement course integration: ```text index.php view.php item.php media.php add.php export.php validate.php lib.php mod_form.php settings.php classes/completion/custom_completion.php classes/local/context_resolver.php classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php classes/output/archive_view.php classes/output/media_library.php classes/output/content_advisory_panel.php classes/privacy/provider.php backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` --- ## 53. Required tests Course integration tests must cover: ```text activity can be created in a course activity resolves context_module course visibility blocks ordinary access activity visibility blocks ordinary access view capability gates activity shell media capability gates media library group mode filters archive records group mode filters media records content advisory policy affects course display cultural protocol restriction blocks unauthorized view public summary excludes restricted media completion respects permissions backup preserves course-owned archive/media records restore remaps course/module/activity ids course import preserves content advisories course export excludes unauthorized files privacy provider exports user data by context pluginfile uses course module context services reject wrong cmid services return filtered data ``` --- ## 54. Final rule This document defines the final target behavior for course integration. ```text Moodle owns the course shell. mod_uckkarchive owns archive/media/content-advisory records inside its module context. Moodle gradebook owns grades. ``` Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/17_integration_with_challenges.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: a2405e65fe9bbcd14ad4360c6b571fa47860124c134b32261c7695f30efe160b CONTENT_BYTES: 20833 ================================================================================================ # 17 — Integration with Challenges **Path:** `docs/17_integration_with_challenges.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Related component:** `mod_uckkchallenge` **Status:** Final target specification **Scope:** Integration contract between the UCKK Archive/Media Library module and the UCKK Challenge module. --- ## 1. Purpose This document defines how `mod_uckkarchive` integrates with challenge activity data. `mod_uckkarchive` is a self-contained Moodle activity module for archive memory, media library management, and content advisory governance. `mod_uckkchallenge` owns challenge workflow. The archive may preserve challenge-related records, media, proofs, review artifacts, provenance, content advisories, and export packages. The archive does not become the challenge workflow authority. Canonical boundary: ```text mod_uckkchallenge = challenge workflow authority mod_uckkarchive = archive/media preservation authority ``` --- ## 2. Core integration decision Challenge integration is reference-based and preservation-based. `mod_uckkarchive` may store: ```text challenge references challenge evidence snapshots challenge submission snapshots challenge review summaries challenge proof records challenge-related media challenge-related content markers challenge-related provenance challenge-related export packages ``` `mod_uckkarchive` must not own: ```text challenge activity setup challenge workflow state challenge grading challenge submission authority challenge attempt lifecycle challenge completion rules challenge evaluator assignment challenge internal review workflow ``` Preservation does not transfer authority. --- ## 3. Ownership boundary ### 3.1 Owned by `mod_uckkchallenge` `mod_uckkchallenge` owns: ```text challenge definition challenge instructions challenge workflow state challenge attempt/submission state challenge participant state challenge review workflow challenge evaluator assignment challenge scoring logic challenge completion logic challenge grading bridge challenge-specific deadlines challenge-specific rules ``` ### 3.2 Owned by `mod_uckkarchive` `mod_uckkarchive` owns: ```text archive items created from challenges challenge-related media records challenge-related media versions challenge-related media collections challenge evidence proof records challenge preservation provenance challenge archive revisions challenge content advisories challenge cultural protocol markers challenge export packages challenge export manifests ``` ### 3.3 Owned by Moodle gradebook Moodle gradebook owns: ```text grades grade items gradebook aggregation grade history final grade display ``` `mod_uckkarchive` does not own grades. --- ## 4. Integration model The integration uses stable references. Archive records may reference challenge records by: ```text sourcecomponent = mod_uckkchallenge sourcearea sourceid sourceuuid sourcetype sourceurl snapshot time ``` Challenge references must be treated as pointers to external authority. The archive stores its own preservation record and provenance around the reference. --- ## 5. Challenge-to-archive preservation A challenge may generate or contribute to archive material. Examples: ```text validated challenge response learner artifact evaluator feedback snapshot challenge proof bundle challenge media submission challenge reflection challenge completion evidence challenge discussion evidence challenge appeal evidence challenge public showcase item ``` These may become archive-owned records when preserved. Archive preservation creates an archive identity. It does not replace the challenge identity. --- ## 6. Archive item types for challenges Challenge-related archive items may use item types such as: ```text challenge_submission_snapshot challenge_review_snapshot challenge_evidence challenge_reflection challenge_media challenge_proof challenge_public_summary challenge_portfolio_item challenge_export_bundle ``` Each preserved item must include enough metadata to explain: ```text which challenge it came from which user or group submitted it which course context applied which moment was preserved who preserved it why it was preserved what version was preserved what visibility applies what restrictions apply ``` --- ## 7. Media integration Challenge-related media is managed as first-class archive media. The media object belongs to `uckkarchive_media`. The original challenge submission remains owned by `mod_uckkchallenge`. The preserved media record may include: ```text media uuid source component source id source version source ownership license metadata rights metadata content advisory markers cultural protocol markers media versions derivatives thumbnails captions transcripts relations collections ``` Media files are stored through Moodle File API under `mod_uckkarchive` when preserved into the archive. The archive must not rely on unmanaged public folders. --- ## 8. Media source values Challenge-related media may use source values such as: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` For challenge submissions, the common source values are: ```text submitted_to_uckk member_submitted partner_submitted external_reference unknown_source ``` Source metadata must not imply ownership where ownership is uncertain. --- ## 9. Media relations for challenges Challenge-related media may use relation types such as: ```text belongs_to_item belongs_to_collection is_proof_for is_source_for is_derivative_of is_translation_of is_excerpt_of references_external_work contains_content_marker ``` Challenge-specific relation examples: ```text media belongs_to_item challenge_submission_snapshot media is_proof_for challenge_completion_evidence media is_source_for challenge_public_summary media is_excerpt_of external_work media contains_content_marker sexual_violence ``` Relations describe archive graph meaning. Relations do not transfer challenge workflow authority to the archive. --- ## 10. Content advisories in challenge integration Challenge artifacts may contain content that requires advisories, cultural protocol, or audience suitability review. `mod_uckkarchive` owns the advisory record once the material is preserved in the archive. Required advisory tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Content advisories may apply to: ```text challenge submission media challenge written response challenge proof file challenge reflection challenge evaluator note external work referenced by a challenge media excerpt used in challenge work public showcase item ``` A content advisory does not ban the challenge artifact. It defines conditions for responsible access, teaching, warning, review, restriction, or contextualization. --- ## 11. Cultural protocol in challenge integration Challenge-related archive records may carry cultural protocol restrictions. Cultural protocol restrictions may affect: ```text who can view a challenge artifact who can view the media original who can view thumbnails or previews who can review cultural notes whether the item can be exported whether the item can appear in a public showcase whether advisory details must be redacted whether elder or community review metadata is required ``` Cultural protocol access requires explicit policy checks. It is not granted automatically by teacher, manager, or administrator status. --- ## 12. External works in challenge integration Challenges may reference works not produced by UCKK. Examples: ```text film book article podcast website external video external image public archive item third-party PDF ``` External works are stored in: ```text uckkarchive_external_work ``` Challenge artifacts may link to external works through content markers, media source records, and archive relations. The archive may store: ```text external work metadata locator references content advisory markers teaching notes cultural protocol notes review state rights notes source references ``` The archive must not imply ownership of third-party works. The archive must not copy external media unless rights and policy allow it. --- ## 13. Locator model Challenge-related content markers may use locators. Locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Examples: ```text Challenge references a film scene -> sexual_violence -> 01:12:30-01:15:10 Challenge references a book excerpt -> trauma -> page 42-45 Challenge PDF submission -> culturally_sensitive -> page 7 Challenge audio reflection -> grief_or_mourning -> 00:08:12-00:09:40 ``` Locator records must be precise enough to support review, warning, and teaching context. --- ## 14. Provenance requirements Every challenge-related archive object must preserve provenance. Required provenance fields include: ```text source component source area source id source uuid when available source type source title source course id source cm id source user id when applicable source group id when applicable snapshot timestamp preserved by userid preservation reason import method file hashes when files are copied visibility at preservation time validation state at preservation time ``` Provenance explains origin. Provenance does not grant authority. --- ## 15. Validation model Challenge validation and archive validation are separate. `mod_uckkchallenge` may determine challenge workflow status. `mod_uckkarchive` may determine archive preservation status. Archive validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Archive validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. --- ## 16. Revision model Challenge records may change after a snapshot is preserved. The archive must preserve its own revision history. Archive revisions may record: ```text metadata correction visibility change content advisory update cultural protocol update media version update provenance correction source challenge reference update redaction update export correction ``` Archive item revisions use: ```text mod/uckkarchive:reviseitem ``` Media versioning uses: ```text mod/uckkarchive:versionmedia ``` The module does not use: ```text mod/uckkarchive:versionitem ``` --- ## 17. Permissions Challenge integration uses both challenge authority and archive authority. When viewing preserved archive records, `mod_uckkarchive` policy applies. When operating on live challenge workflow, `mod_uckkchallenge` policy applies. Archive capabilities involved: ```text mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Media capabilities involved: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Content advisory capabilities involved: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` --- ## 18. Policy checks Challenge-related archive access must check: ```text course module context archive capability archive record visibility media visibility restricted state cultural protocol state content advisory state audience suitability validation state retention state redaction state source ownership export rights ``` Policy classes: ```text classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php ``` Controllers, AMD modules, templates, and forms must not duplicate policy decisions. --- ## 19. Services Challenge integration may require archive services such as: ```text classes/external/add_item.php classes/external/get_archive_item.php classes/external/get_archive_items.php classes/external/update_provenance.php classes/external/validate_item.php classes/external/revise_item.php classes/external/add_media.php classes/external/get_media_item.php classes/external/add_media_version.php classes/external/add_media_relation.php classes/external/add_media_to_collection.php classes/external/get_content_markers.php classes/external/add_content_marker.php classes/external/review_content_marker.php classes/external/add_external_work.php classes/external/export_items.php classes/external/export_media.php ``` Services must never return restricted challenge-derived archive data for client-side hiding. Filtering happens server-side. --- ## 20. Events Challenge-related archive events may include: ```text archive_item_created archive_item_revised archive_item_validated archive_item_exported media_created media_updated media_version_created media_collection_created media_exported content_marker_created content_marker_reviewed external_work_created ``` Events audit archive state changes. Events do not expose restricted content, raw media, private cultural protocol notes, or redacted data. --- ## 21. Backup and restore Archive backup must preserve challenge-related archive records as archive-owned data. Backup may preserve: ```text archive item records challenge source references media records media versions media relations media collections proof records provenance records content markers content reviews external work metadata export manifests ``` Restore must not recreate live challenge workflow state. Restore must not create challenge attempts. Restore must not create grades. Restore may restore source references as references. If the original challenge does not exist after restore, preserved archive records remain valid archive records with historical provenance. --- ## 22. Privacy and retention Challenge-derived archive records may contain personal data. Privacy handling must include: ```text submitter data reviewer data preserver data media contributor data proof contributor data content reviewer data external work curator data restricted notes cultural protocol notes source references ``` Privacy deletion must respect: ```text user rights institutional preservation duties challenge evidence requirements restricted cultural protocol rules integrity restrictions when applicable redaction policy retention policy ``` A privacy request does not automatically delete institutional archive memory. Policy determines export, redaction, anonymization, or retention. --- ## 23. Reporting boundary `mod_uckkarchive` may provide archive-level exports. `report_uckk` owns institutional reporting. Challenge-derived archive exports may include: ```text selected challenge evidence package validated challenge archive bundle media proof bundle content advisory manifest public showcase export restricted review package ``` Institutional reports, dashboards, cross-course metrics, and administrative reporting belong to `report_uckk`. --- ## 24. Grade boundary Challenge artifacts may be related to assessment. `mod_uckkarchive` must not own grade data. The archive may preserve: ```text non-authoritative grade snapshot when explicitly exported review evidence proof of completion public summary portfolio artifact feedback snapshot ``` The authoritative grade remains in Moodle gradebook. --- ## 25. UI integration Archive UI may show challenge-related context. Examples: ```text source challenge title source course source participant source group snapshot timestamp challenge evidence badge content advisory badge cultural protocol badge media count proof count validation state export status ``` UI must not expose: ```text restricted challenge details without policy approval restricted media thumbnails without policy approval restricted advisory details without policy approval private reviewer notes redacted details ``` --- ## 26. Search integration Search and listing must be permission-filtered. Challenge-related archive records must not leak restricted data through: ```text title snippet media thumbnail media preview tag collection content advisory label source challenge reference external work reference count facet autocomplete ``` Redacted placeholders may be used only when policy allows. --- ## 27. Export manifest Challenge-related exports must include manifest metadata. Manifest fields may include: ```text plugin component archive id export id export timestamp export actor export reason source component = mod_uckkchallenge source challenge id source challenge uuid archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections redaction level validation state revision history ``` Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. --- ## 28. Failure behavior If `mod_uckkchallenge` is missing, disabled, or the referenced challenge record is unavailable: ```text preserved archive records remain accessible according to archive policy source reference is shown as unavailable when policy allows archive provenance remains intact live challenge workflow actions are unavailable restore does not attempt to recreate the challenge workflow exports may include historical source metadata when permitted ``` The archive must fail closed for restricted or uncertain access. --- ## 29. Implementation touchpoints Relevant archive files: ```text classes/local/archive_item.php classes/local/archive_policy.php classes/local/proof.php classes/local/provenance.php classes/local/revision.php classes/local/export_package.php ``` Relevant media files: ```text classes/local/media.php classes/local/media_policy.php classes/local/media_relation.php classes/local/media_collection.php classes/local/media_version.php classes/local/media_source.php ``` Relevant content advisory files: ```text classes/local/content_tag.php classes/local/content_tag_set.php classes/local/content_marker.php classes/local/content_review.php classes/local/content_policy.php classes/local/external_work.php ``` Relevant integration files: ```text classes/local/context_resolver.php classes/local/manifest_builder.php classes/local/metadata_validator.php classes/local/uuid.php db/install.xml db/upgrade.php db/services.php db/access.php classes/privacy/provider.php backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` --- ## 30. Tests Challenge integration tests must cover: ```text creating archive items from challenge references preserving challenge source metadata adding media to challenge archive items adding content markers to challenge media linking external works to challenge records permission-filtering restricted challenge archive records cultural protocol restriction behavior media download restrictions archive export manifest generation backup and restore of challenge-derived archive records restore when source challenge is absent privacy export/redaction of challenge-derived records ``` Required test files: ```text tests/archive_test.php tests/media_library_test.php tests/content_advisory_test.php tests/export_test.php tests/backup_restore_test.php tests/privacy_provider_test.php tests/services_test.php tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` --- ## 31. Final integration rule ```text mod_uckkchallenge owns live challenge workflow. mod_uckkarchive owns preserved challenge archive memory. The archive may preserve challenge evidence, media, content advisories, external work references, provenance, validation state, revisions, restricted metadata, and export packages. The archive does not own challenge attempts, challenge workflow state, challenge grading, evaluator assignment, or Moodle gradebook authority. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/18_integration_with_assemblies.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 2e77d08028b7f295724a8dbba70e4b66c8f3d1369730f618137f9a897d4a8ab8 CONTENT_BYTES: 22670 ================================================================================================ # 18 — Integration with Assemblies **Path:** `docs/18_integration_with_assemblies.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Related plugin:** `mod_uckkassembly` **Status:** Final target specification **Scope:** Integration contract between the self-contained UCKK Archive, Media Library, Content Advisory system, and UCKK Assembly workflows. --- ## 1. Purpose This document defines how `mod_uckkarchive` integrates with Assembly workflows. The archive may preserve Assembly-related memory, evidence, media, summaries, minutes, decision snapshots, provenance, content advisories, and export packages. The archive does not own Assembly authority. Canonical rule: ```text mod_uckkassembly owns Assembly procedure and decision authority. mod_uckkarchive owns preserved archive memory about Assembly-related material. ``` The integration must preserve institutional memory without moving decision authority into the archive. --- ## 2. Core integration decision `mod_uckkarchive` is: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` For Assembly integration: ```text mod_uckkassembly = live Assembly workflow, agenda, deliberation, votes, decisions, resolutions, procedural state mod_uckkarchive = preserved Assembly-related archive memory, media, evidence, provenance, advisories, exports ``` The archive can reference Assembly records. The archive can preserve snapshots of Assembly records. The archive can package Assembly-related archive exports. The archive cannot decide Assembly outcomes. --- ## 3. Ownership boundary `mod_uckkassembly` owns: ```text Assembly creation Assembly membership Assembly quorum Assembly agenda Assembly deliberation workflow Assembly motions Assembly votes Assembly decisions Assembly resolutions Assembly minutes as live procedural records Assembly appeals where implemented by Assembly Assembly procedural status Assembly notification workflow Assembly authority state ``` `mod_uckkarchive` owns: ```text archived Assembly snapshots archived Assembly-related media archived Assembly evidence archived Assembly minutes copies archived Assembly public summaries archived Assembly decision summaries archived Assembly provenance archived Assembly validation records archived Assembly content advisories archived Assembly cultural protocol notes archived Assembly external work references archived Assembly export packages ``` Preservation does not transfer authority. --- ## 4. Non-ownership rules `mod_uckkarchive` must not: ```text create Assembly authority change Assembly decisions change Assembly vote records change Assembly quorum status change Assembly membership authority change Assembly procedural status close Assembly disputes approve Assembly resolutions invalidate Assembly decisions replace Assembly minutes as procedural truth act as the Assembly source of truth ``` `mod_uckkarchive` may: ```text preserve a copy of an Assembly decision preserve Assembly evidence preserve Assembly-related media preserve a public summary preserve a restricted summary preserve Assembly provenance preserve a contestation note preserve an invalidation record about an archived copy preserve an export package ``` --- ## 5. Dependency rule Assembly integration is a module integration. Ordinary archive, media library, and content advisory operation must not require `mod_uckkassembly`. When `mod_uckkassembly` is absent: ```text ordinary archive workflows continue ordinary media workflows continue content advisory workflows continue Assembly-specific linking UI is hidden or disabled Assembly-specific service calls fail closed Assembly-specific restoration does not create Assembly authority ``` When `mod_uckkassembly` is present: ```text archive records may reference Assembly records archive records may preserve Assembly snapshots media may be related to Assembly records content advisories may be applied to Assembly-related material exports may include Assembly-related archived material when authorised ``` --- ## 6. Integration model The integration uses reference-based linking. Archive records may store Assembly references using: ```text sourcecomponent = mod_uckkassembly sourcearea = assembly | agenda | minutes | decision | motion | vote | evidence | resolution | summary sourceid = Assembly-side record id sourceuuid = Assembly-side stable uuid when available sourcetitle = human-readable source title sourcetimecreated = source creation time when available sourcetimemodified = source modification time when available ``` Archive records must not require direct ownership of Assembly database tables. The archive should support graceful degradation if the Assembly source record is unavailable. --- ## 7. Assembly archive item types Assembly-related archive items may include: ```text assembly_snapshot assembly_minutes_copy assembly_decision_snapshot assembly_resolution_snapshot assembly_motion_snapshot assembly_evidence_bundle assembly_public_summary assembly_restricted_summary assembly_media_record assembly_provenance_record assembly_contestation_record assembly_export_package ``` These are archive item types, not Assembly procedural records. --- ## 8. Assembly media handling Assembly-related media is managed as first-class media. Media tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` Assembly media may include: ```text meeting recording audio excerpt transcript caption file image document agenda PDF minutes PDF decision scan resolution document evidence file public summary media restricted evidence media external reference media ``` Media files remain in Moodle File API file areas. Media identity, metadata, relations, source, lifecycle, and advisories remain in archive-owned tables. --- ## 9. Assembly media source Assembly-related media must identify its source. Media source table: ```text uckkarchive_media_source ``` Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Assembly media source rule: ```text The archive preserves source and rights context. The archive does not imply ownership over third-party or external works. ``` --- ## 10. Assembly content advisory integration Assembly-related archive material may require content advisories. Content advisory tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review ``` Assembly content advisories may apply to: ```text meeting recording minutes transcript motion text evidence file public summary restricted summary external work reference media excerpt decision context ``` Advisory examples: ```text sexual_violence violence racism colonial_violence death self_harm substance_use culturally_sensitive sacred_content ceremonial_content restricted_knowledge grief_or_mourning requires_context not_for_children ``` Content advisory rule: ```text A content advisory does not ban Assembly material. It describes responsible warning, teaching context, access conditions, restriction, review, or cultural protocol. ``` --- ## 11. Cultural protocol integration Assembly material may contain culturally sensitive or restricted content. Cultural protocol tags may include: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Cultural protocol workflow: ```text identify cultural protocol concern → create content marker → attach cultural protocol tag → set visibility = restricted_cultural when required → require human review → preserve review decision → enforce access policy ``` AI cannot approve cultural protocol access. Archive policy must enforce cultural protocol restrictions independently from ordinary visibility. --- ## 12. Assembly content markers Content markers link advisories to precise locations. A marker may point to: ```text Assembly-related media object Assembly-related media version Assembly archive item Assembly transcript Assembly minutes copy Assembly evidence bundle Assembly external work reference manual Assembly reference ``` Locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Examples: ```text Assembly recording -> grief_or_mourning -> 00:18:12-00:21:40 Assembly minutes PDF -> culturally_sensitive -> page 7 Assembly evidence bundle -> sexual_violence -> document 3, page 2 External film discussed in Assembly -> sexual_violence -> 01:12:30-01:15:10 Book discussed in Assembly -> sexual_violence -> page 42-45 ``` --- ## 13. External works in Assembly context Assembly may discuss or rely on works not produced by UCKK. External work table: ```text uckkarchive_external_work ``` External work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External work workflow: ```text create external work reference → record bibliographic/source metadata → record source ownership → add content markers where needed → add advisory tags → link to Assembly archive item → preserve reference without claiming ownership ``` External/foreign media rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` --- ## 14. Assembly provenance Assembly-related archive items must preserve provenance. Provenance values may include: ```text assembly human imported system ai_assisted external_work content_review media ``` Assembly provenance must record where applicable: ```text Assembly source component Assembly source record id Assembly source uuid source title source timestamp archiving actor archiving timestamp validation actor validation timestamp reason for preservation file hashes snapshot hash revision id export id ``` Provenance explains origin. Provenance does not grant Assembly authority. --- ## 15. Assembly validation Archive validation confirms that the archived Assembly-related record is reliable as preserved memory. Archive validation does not validate the Assembly decision itself. Validation distinction: ```text Assembly decision validity = mod_uckkassembly Archive copy reliability = mod_uckkarchive ``` Archive validation may confirm: ```text snapshot completeness file integrity metadata accuracy source reference accuracy visibility policy content advisory markers cultural protocol review export eligibility ``` Archive validation uses: ```text mod/uckkarchive:validateitem ``` AI cannot validate Assembly-related archive records. --- ## 16. Assembly restriction handling Assembly-related archive records may be restricted for: ```text privacy minor safety integrity sensitivity cultural protocol content advisory severity copyright external rights unvalidated provenance contested record confidential deliberation ``` Visibility values used for Assembly archive material: ```text private group course program institution public restricted restricted_integrity restricted_cultural ``` Restriction rule: ```text Restricted Assembly archive records remain preserved. Restriction controls access, download, export, display, and metadata exposure. ``` --- ## 17. Assembly contestation Archive contestation records disagreement, uncertainty, objection, or review challenge about the archived copy. Archive contestation may apply to: ```text archived minutes copy archived decision snapshot archived resolution snapshot public summary restricted summary media metadata content advisory marker cultural protocol note external work reference provenance claim ``` Archive contestation does not change the live Assembly decision. If the Assembly decision itself is contested, the authoritative contestation workflow belongs to `mod_uckkassembly`. The archive may preserve a contestation record or snapshot. --- ## 18. Assembly export packages `mod_uckkarchive` may export Assembly-related archive packages. Export package may include: ```text archive item metadata Assembly source references decision snapshots minutes copies media objects media versions proofs Kristals provenance revision history content advisory markers content reviews external work references redaction metadata manifest.json ``` Export must not include: ```text unauthorised restricted media unauthorised culturally restricted content unauthorised integrity-restricted content private Assembly procedural data outside archive authority live Assembly workflow state as authority ``` Export rule: ```text Export packages are portable archive memory. Export packages do not become Assembly procedural authority. ``` --- ## 19. Export manifest requirements Assembly-related exports must include Assembly integration metadata in `manifest.json`. Required manifest fields where applicable: ```text plugin component archive id archive item uuid export id export timestamp export actor sourcecomponent = mod_uckkassembly sourcearea sourceid sourceuuid sourcetitle media uuids media version uuids external work uuids content marker uuids content review state file hashes visibility restricted flags audience suitability cultural protocol flags provenance relations redaction level validation state revision history ``` Manifest rule: ```text The manifest explains what was preserved and why. It does not grant access beyond policy. ``` --- ## 20. Backup and restore behavior Backup includes Assembly-related archive-owned records. Backup may include: ```text archive item records media records media versions media relations media collections content markers content reviews external work references media source records provenance records revision records export records File API files ``` Restore reconstructs archive-owned records. Restore must not: ```text create live Assembly decisions create Assembly votes create Assembly quorum records create Assembly procedural authority create Assembly membership authority ``` Restore may preserve: ```text sourcecomponent sourcearea sourceid sourceuuid archived snapshots archived references ``` If matching Assembly source records are unavailable after restore, archive records remain valid as preserved archive memory with unresolved source references. --- ## 21. Privacy behavior Assembly-related archive material may contain personal, sensitive, cultural, or restricted data. Privacy provider must cover user-linked data in: ```text archive items proofs Kristals media objects media versions media relations media collections content markers content reviews external work notes where user-linked provenance revisions exports files ``` Privacy rule: ```text Privacy export describes archive-held data. Privacy deletion/anonymisation must respect retention, institutional memory, cultural protocol, and legal/ethical preservation requirements. ``` The archive privacy provider does not manage live Assembly records owned by `mod_uckkassembly`. --- ## 22. Events and audit Assembly-related archive workflows may trigger archive events: ```text archive_item_created archive_item_validated archive_item_revised archive_item_exported media_created media_updated media_version_created content_marker_created content_marker_reviewed external_work_created ``` Events must include: ```text context object id related user where safe sourcecomponent where applicable sourcearea where applicable ``` Events must not expose: ```text raw restricted content private cultural protocol notes redacted details unauthorised Assembly evidence confidential deliberation material ``` --- ## 23. Service contract Assembly integration services must use Moodle external service patterns. Services must: ```text require login resolve context validate parameters check capabilities call archive policy call media policy call content policy return permission-filtered data fail closed when Assembly source is unavailable ``` Assembly integration service behavior may be implemented inside broader archive/media services using source references. Dedicated Assembly service names may be added if needed: ```text classes/external/get_assembly_archive_items.php classes/external/link_assembly_item.php classes/external/create_assembly_snapshot.php classes/external/export_assembly_archive.php ``` All services must keep Assembly authority outside the archive. --- ## 24. UI behavior The archive UI may show Assembly-related data as archive memory. UI may display: ```text Assembly source reference archived title archived summary decision snapshot label minutes copy label media links content advisory badges cultural protocol badges restriction badges validation state revision history export availability ``` UI must not display Assembly-related archive material as the live Assembly source of truth unless explicitly labelled as a preserved snapshot. Required labels: ```text Archived Assembly snapshot Archived copy Source reference Preserved evidence Restricted Assembly archive record Culturally restricted Assembly archive record ``` --- ## 25. Capability map Archive capabilities used in Assembly integration: | Workflow | Capability | |---|---| | View Assembly-related archive item | `mod/uckkarchive:view` | | Add Assembly-related archive item | `mod/uckkarchive:additem` | | Validate Assembly-related archive item | `mod/uckkarchive:validateitem` | | Revise Assembly-related archive item | `mod/uckkarchive:reviseitem` | | View restricted Assembly archive item | `mod/uckkarchive:viewrestricted` | | Export Assembly archive package | `mod/uckkarchive:export` | Media capabilities used in Assembly integration: | Workflow | Capability | |---|---| | View Assembly media | `mod/uckkarchive:viewmedia` | | Add Assembly media | `mod/uckkarchive:addmedia` | | Edit Assembly media | `mod/uckkarchive:editmedia` | | Download Assembly media | `mod/uckkarchive:downloadmedia` | | Add Assembly media version | `mod/uckkarchive:versionmedia` | | Export Assembly media | `mod/uckkarchive:exportmedia` | | View restricted Assembly media | `mod/uckkarchive:viewrestrictedmedia` | Content advisory capabilities used in Assembly integration: | Workflow | Capability | |---|---| | View Assembly content advisories | `mod/uckkarchive:viewadvisories` | | Manage Assembly content advisories | `mod/uckkarchive:manageadvisories` | | Review Assembly content advisories | `mod/uckkarchive:reviewadvisories` | | View culturally restricted Assembly material | `mod/uckkarchive:viewculturallyrestricted` | | Manage external works referenced by Assembly | `mod/uckkarchive:manageexternalworks` | Capabilities are gates. Policy classes remain authoritative. --- ## 26. Local class dependencies Assembly integration depends on archive classes: ```text classes/local/archive_item.php classes/local/archive_policy.php classes/local/provenance.php classes/local/revision.php classes/local/export_package.php classes/local/manifest_builder.php ``` Assembly media integration depends on media classes: ```text classes/local/media.php classes/local/media_policy.php classes/local/media_version.php classes/local/media_relation.php classes/local/media_collection.php classes/local/media_source.php classes/local/media_file.php ``` Assembly content advisory integration depends on content classes: ```text classes/local/content_tag.php classes/local/content_tag_set.php classes/local/content_marker.php classes/local/content_review.php classes/local/content_policy.php classes/local/external_work.php ``` Shared dependencies: ```text classes/local/context_resolver.php classes/local/file_area_registry.php classes/local/metadata_validator.php classes/local/uuid.php ``` --- ## 27. File areas Assembly-related archive material may use archive file areas: ```text item_files decision_attachments minutes_files proof_files kristal_files provenance_files validation_files revision_files export_package export_manifest ``` Assembly-related media uses media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Assembly content advisory support files may use: ```text content_review_files external_work_reference_files cultural_protocol_files ``` All files must be stored through Moodle File API. No production Assembly archive or media files are stored in unmanaged public folders. --- ## 28. Testing requirements Tests must verify: ```text Assembly source references can be stored Assembly source absence fails safely Assembly snapshots do not create Assembly authority Assembly-related media is permission-filtered Assembly-related content advisories are permission-filtered cultural restrictions are enforced exports include Assembly source metadata exports do not leak restricted Assembly material backup preserves archive-owned Assembly references restore does not create live Assembly authority privacy provider covers user-linked Assembly archive records ``` Suggested test files: ```text tests/archive_test.php tests/media_library_test.php tests/content_advisory_test.php tests/backup_restore_test.php tests/export_test.php tests/privacy_provider_test.php tests/services_test.php tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` --- ## 29. Final integration rule ```text Assembly owns decisions. Archive owns preserved memory. Media library owns reusable media objects. Content advisory system owns suitability, warning, cultural protocol, and locator metadata. Provenance explains origin. Validation confirms archive reliability, not Assembly authority. Exports package only what policy allows. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/19_integration_with_integrity.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: a790c21cbff517f62157c16000b6aa388c126dfd000864f052edb947e039a6ac CONTENT_BYTES: 22041 ================================================================================================ # 19 — Integration with Integrity **Path:** `docs/19_integration_with_integrity.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Related component:** `tool_uckkintegrity` **Status:** Final target specification **Scope:** Optional integration between the UCKK Archive/Media Library module and the UCKK Integrity tool. --- ## 1. Purpose This document defines how `mod_uckkarchive` integrates with integrity-related workflows while preserving clear domain ownership. `mod_uckkarchive` is a self-contained Moodle activity module for archive memory, media library management, and content advisory governance. `tool_uckkintegrity` is the integrity procedure authority. The integration is optional. Ordinary archive, media, and content advisory workflows must work without `tool_uckkintegrity`. --- ## 2. Core decision Canonical integration rule: ```text tool_uckkintegrity owns integrity procedure. mod_uckkarchive owns archive/media preservation. ``` `mod_uckkarchive` may preserve: ```text integrity-related archive items integrity-related media integrity evidence bundles restricted summaries proof files content advisories content markers provenance revision history validation state export packages export manifests ``` `mod_uckkarchive` must not own: ```text integrity case authority integrity investigation procedure integrity findings integrity sanctions integrity appeal workflow integrity case closure integrity officer assignment integrity procedural deadlines ``` Preservation does not transfer authority. --- ## 3. Dependency rule `tool_uckkintegrity` is optional. Dependency rule: ```text tool_uckkintegrity = optional integration ordinary archive/media/content-advisory operation must not require tool_uckkintegrity integrity-specific features must be hidden, disabled, or fail closed when tool_uckkintegrity is absent ``` The plugin must not declare a hard runtime dependency on `tool_uckkintegrity` unless a future release intentionally changes the architecture. Allowed behavior when `tool_uckkintegrity` is absent: ```text archive items continue to work media library continues to work content advisories continue to work external works continue to work ordinary exports continue to work integrity-specific links are unavailable integrity-specific import/sync is disabled integrity-specific restricted views fail closed ``` --- ## 4. Architecture boundary Canonical ownership: ```text INTEGRITY_OWNER = tool_uckkintegrity ARCHIVE_OWNER = mod_uckkarchive ``` Boundary rules: ```text mod_uckkarchive can reference integrity cases. mod_uckkarchive can preserve integrity-related evidence. mod_uckkarchive can preserve integrity-related media. mod_uckkarchive can preserve integrity-related summaries. mod_uckkarchive can preserve integrity-related exports. mod_uckkarchive can apply restricted visibility to integrity-related records. mod_uckkarchive can record provenance showing integrity origin. mod_uckkarchive cannot decide the integrity case. mod_uckkarchive cannot replace the integrity workflow. mod_uckkarchive cannot become the integrity case registry. ``` --- ## 5. Integration object model Integrity references in `mod_uckkarchive` must be stored as archive-owned references, not as copied procedure authority. Archive-owned records may include: ```text sourcecomponent = tool_uckkintegrity sourcearea = case | evidence | finding_summary | export | note | attachment sourceid = external integrity record id sourceuuid = external integrity UUID when available sourcelabel = human-readable reference sourcetimecreated = source creation timestamp when available sourcetimemodified = source modification timestamp when available ``` Reference rule: ```text Integrity source references identify origin. They do not make mod_uckkarchive the procedural authority. ``` --- ## 6. Archive item integration Integrity-related archive items may represent: ```text case evidence snapshot restricted case summary integrity media bundle integrity proof record integrity export record integrity timeline snapshot appeal-supporting archive material redacted public summary validated institutional memory item ``` Archive item fields should support: ```text type = integrity_summary | integrity_evidence | integrity_export | proof | media_bundle | restricted_summary visibility = restricted_integrity validationstate = unverified | human_reviewed | verified | contested | invalidated | archived provenance = integrity ``` Archive item rule: ```text An integrity-related archive item preserves a record or snapshot. It does not become the active integrity case. ``` --- ## 7. Media integration Integrity-related media is managed through the normal media library model. Relevant tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item uckkarchive_media_source ``` Integrity media source values may include: ```text submitted_to_uckk imported restricted_reference external_reference_only ``` Integrity media visibility should normally use: ```text restricted_integrity restricted private staff_only ``` Media rule: ```text Integrity-related media remains a media object. It is not stored as unmanaged evidence files outside Moodle File API. ``` --- ## 8. File API integration Integrity-related files are stored through Moodle File API under `mod_uckkarchive`. Relevant archive file areas: ```text integrity_exports proof_files item_files decision_attachments provenance_files validation_files revision_files export_package export_manifest ``` Relevant media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Relevant content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File rule: ```text Integrity files preserved by mod_uckkarchive are archive/media files. They are not live integrity procedure files unless explicitly accessed from tool_uckkintegrity. ``` --- ## 9. Restricted integrity visibility Canonical visibility value: ```text restricted_integrity ``` Restricted integrity visibility applies to: ```text archive items media objects media versions media collections content markers content reviews external work references export packages manifest entries proof records provenance records revision records ``` Restricted integrity rule: ```text restricted_integrity records must not leak through search, thumbnails, previews, export manifests, course displays, backup previews, events, logs, or AJAX responses. ``` --- ## 10. Capability model Archive capabilities relevant to integrity integration: ```text mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Media capabilities relevant to integrity integration: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Content advisory capabilities relevant to integrity integration: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories ``` Restricted cultural capability may also apply where cultural protocol intersects with integrity evidence: ```text mod/uckkarchive:viewculturallyrestricted ``` Capability rule: ```text Capabilities are gates, not full authority. Policy classes still enforce context, ownership, visibility, status, validation state, restricted state, content advisory rules, cultural protocol rules, retention, and redaction. ``` --- ## 11. Policy enforcement Archive policy: ```text classes/local/archive_policy.php ``` Media policy: ```text classes/local/media_policy.php ``` Content advisory policy: ```text classes/local/content_policy.php ``` Integrity integration policy may be implemented as: ```text classes/local/integrity_link.php classes/local/integrity_policy.php ``` Policy checks must include: ```text context access course module visibility capability gates source component availability integrity integration enabled state restricted_integrity visibility restricted media visibility content advisory status cultural protocol restrictions retention requirements redaction requirements export authorization download authorization search visibility preview visibility thumbnail visibility ``` Policy rule: ```text Integrity-linked records fail closed when authority cannot be verified. ``` --- ## 12. Content advisory integration Integrity-related records may contain sensitive material. The content advisory subsystem must support integrity-related advisories through: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review ``` Relevant advisory examples: ```text sexual_violence violence racism colonial_violence death self_harm substance_use explicit_language culturally_sensitive restricted_knowledge grief_or_mourning requires_context not_for_children ``` Integrity-sensitive tag set examples: ```text integrity_sensitive restricted_case_material investigation_evidence appeal_sensitive witness_sensitive ``` Content advisory rule: ```text A content advisory does not decide the integrity case. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 13. Content marker integration Integrity-related content markers may point to: ```text media object media version archive item proof record external work manual reference ``` Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Examples: ```text Evidence video -> violence -> 00:02:10-00:03:45 Case PDF -> restricted_integrity -> page 8-12 External article -> racism -> url_fragment #section-2 Witness audio -> grief_or_mourning -> 00:08:12-00:09:40 ``` Content marker rule: ```text Integrity-related content markers must respect restricted_integrity visibility and must not expose sensitive locator details to unauthorized users. ``` --- ## 14. Cultural protocol intersection Some integrity-related records may also be culturally restricted. Relevant visibility: ```text restricted_cultural restricted_integrity ``` Relevant capability: ```text mod/uckkarchive:viewculturallyrestricted ``` Cultural protocol examples: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required not_for_public_export requires_context ``` Intersection rule: ```text When restricted_integrity and restricted_cultural both apply, the stricter access rule wins. ``` Cultural protocol rule: ```text Restricted cultural material must not become public through integrity export, archive export, search, thumbnails, previews, backup preview, or course display. ``` --- ## 15. Import from integrity tool When `tool_uckkintegrity` is installed and integration is enabled, `mod_uckkarchive` may import or snapshot integrity records. Import workflow: ```text 1. Authorized user requests integrity import or snapshot. 2. System verifies tool_uckkintegrity exists and integration is enabled. 3. Integrity source record is located through approved API or service. 4. Archive policy checks permission to preserve the source. 5. Media policy checks permission to preserve files or references. 6. Content policy checks sensitive advisory defaults. 7. Archive item is created or updated. 8. Media objects are created or linked. 9. Provenance records source component, source id, actor, and timestamp. 10. Restricted visibility is applied by default. 11. Import event or archive event is triggered. ``` Import rule: ```text Imports create archive/media snapshots. They do not move the integrity case into mod_uckkarchive. ``` --- ## 16. Export to integrity tool `mod_uckkarchive` may provide archive/media records to `tool_uckkintegrity` only through explicit authorized workflow. Export-to-integrity workflow: ```text 1. Authorized user selects archive/media material. 2. Export preview is generated. 3. Policy checks export authority and restricted access. 4. Content advisories and redaction rules are applied. 5. Export package or reference bundle is generated. 6. tool_uckkintegrity receives references or package through approved integration. 7. Provenance and export manifest are preserved. ``` Export-to-integrity rule: ```text mod_uckkarchive may supply records to an integrity process. It does not decide how tool_uckkintegrity uses them procedurally. ``` --- ## 17. Provenance integration Integrity-related archive/media records must preserve provenance. Canonical provenance value: ```text integrity ``` Provenance metadata should include: ```text source component source area source id source uuid source label source timestamp import actor import timestamp review actor review timestamp hash values manifest reference restriction state redaction state ``` Provenance rule: ```text Provenance explains origin. Provenance does not grant authority by itself. ``` --- ## 18. Validation integration Archive validation is human-final. Canonical validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Validation rule: ```text Validation of an archive record does not validate or close the integrity case. It validates the archive record as preserved material. ``` AI rule: ```text AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. AI cannot decide integrity outcomes. ``` --- ## 19. Revision integration Integrity-linked archive records and media must remain revisionable. Archive item revision uses: ```text mod/uckkarchive:reviseitem ``` Media versioning uses: ```text mod/uckkarchive:versionmedia ``` Removed capability: ```text mod/uckkarchive:versionitem = not used ``` Revision rule: ```text Integrity-linked records must not be silently overwritten. Corrections, replacements, redactions, and metadata changes must preserve revision history. ``` --- ## 20. Search integration Search may include integrity-linked records only when authorized. Search dimensions may include: ```text archive type media type source component source reference restricted state content advisory tag collection provenance validation state review state ``` Search rule: ```text Unauthorized users must not see restricted_integrity records in results, counts, facets, snippets, thumbnails, previews, or advisory summaries. ``` --- ## 21. UI integration Integrity-related UI appears only when relevant and authorized. Possible UI elements: ```text integrity source badge restricted integrity label provenance panel content advisory panel redaction status export preview warning media relation graph external work card ``` UI rule: ```text Server-side policy is authoritative. Client-side UI is never the security boundary. ``` --- ## 22. Events and audit Integrity-related archive/media events may include: ```text archive_item_created archive_item_revised archive_item_validated archive_item_exported media_created media_updated media_version_created media_exported content_marker_created content_marker_reviewed ``` Optional integration-specific events may include: ```text integrity_snapshot_created integrity_reference_linked integrity_export_created ``` Event rule: ```text Events audit successful state changes. Events must not expose restricted integrity content, raw evidence, private notes, cultural protocol details, or redacted information. ``` --- ## 23. Backup and restore Backup must include archive-owned integrity references and preserved records. Backup may include: ```text archive items media records media versions media files proof records provenance revisions content advisories content markers content reviews external works media sources collections relations export manifests restricted_integrity visibility ``` Backup must not include: ```text live integrity procedure state owned by tool_uckkintegrity integrity officer assignment state case deadlines active procedural decisions sanction execution workflow appeal workflow state unless preserved as archive snapshot ``` Restore rule: ```text Restore preserves archive-owned records. Restore must not recreate or claim authority over live integrity cases. Restore must not make restricted_integrity records public. ``` --- ## 24. Privacy and retention Privacy provider: ```text classes/privacy/provider.php ``` Privacy coverage includes archive-owned integrity-related: ```text archive items media records media versions proof records content markers content reviews external work references media source records provenance revisions exports ``` Privacy rule: ```text Privacy export is not a permission bypass. Restricted integrity evidence, third-party information, witness information, cultural protocol notes, and redacted data must be filtered or redacted. ``` Retention rule: ```text Integrity-linked records may require preservation even when ordinary media would be deleted. Retention policy must be checked before purge. ``` --- ## 25. Reporting boundary `mod_uckkarchive` owns archive/media export packages. `report_uckk` owns institutional reporting. `tool_uckkintegrity` owns integrity procedure. Reporting boundary: ```text mod_uckkarchive may expose archive-owned records to report_uckk when authorized. report_uckk may aggregate institutional views. tool_uckkintegrity remains the integrity authority. ``` Reporting rule: ```text Integrity-linked archive/media data must not become available in institutional reports unless reporting policy, restricted visibility, redaction, and authority checks allow it. ``` --- ## 26. External services Integrity integration services should be explicit and permission-gated. Possible service files: ```text classes/external/get_integrity_links.php classes/external/link_integrity_reference.php classes/external/import_integrity_snapshot.php classes/external/export_to_integrity.php ``` Service rules: ```text Services must check tool availability. Services must check integration enabled state. Services must check context. Services must check capabilities. Services must check restricted_integrity visibility. Services must check cultural protocol restrictions. Services must check content advisory review state. Services must filter output. Services must fail closed. ``` No service may expose raw integrity evidence without policy approval. --- ## 27. Settings Plugin settings may include: ```text enableintegrityintegration allowintegritysnapshots allowintegrityexports defaultintegrityvisibility defaultintegrityredaction showintegritybadges ``` Default values should be conservative: ```text enableintegrityintegration = disabled unless explicitly enabled defaultintegrityvisibility = restricted_integrity defaultintegrityredaction = enabled showintegritybadges = authorized users only ``` Settings rule: ```text Settings can enable integration surfaces. Settings cannot bypass context, capability, privacy, redaction, cultural protocol, or retention policy. ``` --- ## 28. Failure modes When `tool_uckkintegrity` is missing: ```text ordinary archive workflows continue ordinary media workflows continue ordinary content advisory workflows continue integrity import is disabled integrity export-to-tool is disabled integrity live reference refresh is disabled stored archive snapshots remain available according to policy ``` When an integrity source reference cannot be resolved: ```text stored archive snapshot remains preserved live source refresh fails closed UI displays unavailable source to authorized users only export manifest records unresolved source reference when authorized ``` When permission cannot be verified: ```text access is denied download is denied export is denied thumbnail/preview is denied search leak is prevented ``` --- ## 29. Testing requirements Tests must cover: ```text archive works without tool_uckkintegrity media library works without tool_uckkintegrity content advisories work without tool_uckkintegrity integrity features hidden when tool absent restricted_integrity visibility enforced restricted_integrity not leaked in search restricted_integrity not leaked in thumbnails/previews restricted_integrity not leaked in exports integrity snapshot preserves provenance integrity snapshot does not create live case authority backup/restore preserves restricted state privacy export redacts restricted data content advisory review required cultural restriction overrides ordinary access ``` Recommended test files: ```text tests/integration_integrity_test.php tests/content_advisory_test.php tests/media_library_test.php tests/backup_restore_test.php tests/privacy_provider_test.php tests/services_test.php tests/behat/uckkarchive_integrity.feature ``` Testing rule: ```text Tests verify the final target behavior, not historical transitions. ``` --- ## 30. Final integration rule ```text mod_uckkarchive integrates with tool_uckkintegrity only as an optional archive/media preservation and reference layer. tool_uckkintegrity remains the integrity procedure authority. mod_uckkarchive may preserve evidence, media, content advisories, provenance, revisions, restricted summaries, external references, and export packages. mod_uckkarchive must not decide, close, replace, or own integrity procedure. This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ``` ================================================================================================ FILE: mod/uckkarchive/docs/20_reporting_and_exports.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 918600e4310f70586ed15b2bad1c14d22baa359600fe673f9fe3422daf658b5c CONTENT_BYTES: 28398 ================================================================================================ # 20 — Reporting and Exports **Path:** `docs/20_reporting_and_exports.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Related plugin:** `report_uckk` **Status:** Final target specification **Scope:** Archive-owned exports, media-library exports, content advisory export behavior, external work references, export manifests, reporting boundaries, redaction, portability, and separation from institutional reporting. --- ## 1. Purpose This document defines the reporting and export contract for `mod_uckkarchive`. `mod_uckkarchive` is a self-contained Moodle activity module for: ```text archive memory media library management content advisory governance cultural sensitivity tagging external/foreign media references exportable archive/media packages ``` This document defines what `mod_uckkarchive` may export, what it must not export, how exports are represented, how export manifests are built, and how reporting boundaries are preserved. --- ## 2. Core architecture rule Canonical architecture formula: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` Export architecture follows the same rule. `mod_uckkarchive` uses Moodle for: ```text context users roles capabilities File API Privacy API Backup API Restore API events scheduled tasks external services ``` Inside that Moodle boundary, `mod_uckkarchive` owns archive/media/content-advisory export packages. --- ## 3. Reporting boundary decision `mod_uckkarchive` owns archive/media export packages. `report_uckk` owns institutional reports. Canonical boundary: ```text mod_uckkarchive = archive-owned export packages report_uckk = institutional reporting views and institutional report exports ``` `mod_uckkarchive` may export selected archive/media records that it owns. `report_uckk` may aggregate, filter, display, and export cross-plugin institutional reporting views. The archive module does not become the institutional reporting authority. --- ## 4. External ownership map Canonical ownership boundaries: ```text Moodle gradebook = grades local_uckk = shared UCKK registry and institutional configuration mod_uckkchallenge = challenge workflow mod_uckkassembly = assembly workflow and decisions tool_uckkintegrity = integrity procedures and case records report_uckk = institutional reporting views and institutional report exports mod_uckkarchive = archive/media/content-advisory memory layer ``` `mod_uckkarchive` does not own: ```text grades transcripts course enrolment authority administrative registry records challenge workflow state Assembly decision authority integrity case authority institutional reporting authority ``` Preserved evidence does not transfer authority. Referenced external works do not become UCKK-owned works. --- ## 5. Archive export ownership `mod_uckkarchive` may own and generate exports for: ```text archive item exports selected item exports validated item exports public item exports restricted item exports when authorized proof bundles Kristal bundles provenance bundles revision bundles media bundles media collection bundles content advisory bundles external work reference bundles export manifests archive export package files ``` These exports are archive-owned packages. They are not institutional reports. --- ## 6. Institutional reporting boundary `report_uckk` owns: ```text institutional dashboards cross-course reports cross-plugin reports cohort reports program reports administrative reports grade reports activity reports across plugins institutional export views institutional reporting permissions ``` `mod_uckkarchive` may provide archive data to `report_uckk` through safe APIs or database views when designed. `mod_uckkarchive` must not duplicate `report_uckk` as a reporting dashboard. --- ## 7. Export package types Canonical archive/media export package types: ```text archive_item_export archive_selection_export archive_collection_export media_item_export media_selection_export media_collection_export proof_bundle_export kristal_bundle_export provenance_export revision_export content_advisory_export external_work_reference_export restricted_archive_export restricted_integrity_export ``` Export package type rule: ```text Export type describes the package purpose. Export type does not bypass permission, redaction, visibility, cultural protocol, or retention policy. ``` --- ## 8. Required export tables Primary export table: ```text uckkarchive_export ``` Export records may reference: ```text uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Export record rule: ```text The export record stores the export request, policy result, manifest reference, file reference, actor, timestamps, status, and redaction level. ``` --- ## 9. Export package lifecycle Canonical export package statuses: ```text requested queued generating ready failed expired revoked deleted_soft ``` Status meaning: | Status | Meaning | |---|---| | `requested` | Export request has been submitted. | | `queued` | Export is waiting for scheduled task or worker processing. | | `generating` | Export package is being generated. | | `ready` | Export package is available under policy. | | `failed` | Export generation failed and error metadata is available to authorized users. | | `expired` | Export package is no longer downloadable under retention policy. | | `revoked` | Export access was explicitly withdrawn. | | `deleted_soft` | Export package is hidden and retained only as policy requires. | Lifecycle rule: ```text Export readiness is not export authority. A ready package still requires permission checks before download. ``` --- ## 10. Export file areas Canonical export file areas: ```text export_package export_manifest ``` Export file areas belong to: ```text component = mod_uckkarchive ``` File-area rule: ```text Export package files and manifest files are stored through Moodle File API. No production export package is stored in unmanaged public folders. ``` Export package files may include: ```text ZIP files JSON files CSV files PDF summary files HTML index files manifest files redacted media copies allowed original media copies allowed derivative media copies allowed transcript/caption files reference-only external work records ``` --- ## 11. Export manifest Every export package must include a manifest. Canonical manifest filename: ```text manifest.json ``` The manifest is the authoritative description of the package contents. Manifest includes: ```text plugin component plugin version archive id export id export uuid export type export timestamp export actor export reason course id course module id context id archive item ids archive item uuids media uuids media version uuids media collection uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Manifest rule: ```text Exports are portable and explainable. Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` --- ## 12. Manifest redaction The manifest must be redaction-aware. Manifest fields may be: ```text included summarized redacted omitted reference_only ``` Restricted manifest data includes: ```text private reviewer notes private cultural protocol notes integrity details restricted media metadata restricted archive metadata sensitive content advisory notes third-party rights notes not safe to share personal data not authorized for export ``` Manifest redaction rule: ```text A manifest may explain that redaction occurred without exposing the redacted content. ``` --- ## 13. Export capability model Archive export capability: ```text mod/uckkarchive:export ``` Media export capability: ```text mod/uckkarchive:exportmedia ``` Restricted archive access capability: ```text mod/uckkarchive:viewrestricted ``` Restricted media access capability: ```text mod/uckkarchive:viewrestrictedmedia ``` Content advisory view capability: ```text mod/uckkarchive:viewadvisories ``` Content advisory management capability: ```text mod/uckkarchive:manageadvisories ``` Culturally restricted view capability: ```text mod/uckkarchive:viewculturallyrestricted ``` Capability rule: ```text Capabilities are gates, not full authority. Policy classes still enforce context, ownership, visibility, status, validation state, restricted state, content advisory rules, cultural protocol rules, retention, and redaction. ``` --- ## 14. Export policy classes Archive export policy belongs in: ```text classes/local/archive_policy.php ``` Media export policy belongs in: ```text classes/local/media_policy.php ``` Content advisory export policy belongs in: ```text classes/local/content_policy.php ``` Manifest construction belongs in: ```text classes/local/manifest_builder.php ``` Export package creation belongs in: ```text classes/local/export_package.php ``` Policy classes decide: ```text whether export is allowed which records are included which files are included which media versions are included which advisories are included which cultural protocol fields are redacted which external works are reference-only which fields are redacted which manifest entries are included which package format is allowed whether package download is allowed ``` --- ## 15. Archive item export Archive item export may include: ```text archive item metadata archive item public summary archive item body/content status visibility validation state provenance revision history linked proofs linked Kristals linked media references content advisory summaries export-safe content markers export-safe review state allowed files manifest entry ``` Archive item export must not include: ```text restricted metadata without authority private review notes without authority unredacted cultural protocol notes without authority integrity case details without authority unauthorized media files unauthorized external work copies ``` --- ## 16. Media export Media export may include: ```text media metadata media source metadata media version metadata allowed original files allowed derivative files allowed preview files allowed thumbnails allowed captions allowed transcripts media relations media tags media collection membership content advisory markers content review state external work references manifest entry ``` Media export must respect: ```text media status media visibility media source classification download authority export authority cultural protocol restrictions third-party rights metadata redaction policy ``` Media export rule: ```text A user who can view a media card is not automatically allowed to export the original media file. ``` --- ## 17. Media collection export Media collection export may include: ```text collection metadata collection membership collection order media object references media version references allowed files media relations content advisory summaries content marker references external work references manifest entry ``` Collection export rule: ```text Collection membership does not override media item policy. Each media item remains independently permission-filtered. ``` --- ## 18. Content advisory export Content advisory export may include: ```text content tag keys content tag display names content tag set keys content marker locators severity audience suitability review state public teaching context redacted review notes cultural protocol flags manifest entries ``` Content advisory export must not expose: ```text private reviewer notes private cultural protocol notes restricted knowledge community permission notes without authority integrity-sensitive notes without authority unapproved AI-suggested markers as approved records ``` Architecture rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 19. Cultural protocol export Cultural protocol data must be exported only when policy allows. Cultural protocol-related tags may include: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Cultural protocol export decisions may be: ```text include include_summary_only include_flag_only redact_private_notes omit block_export ``` Cultural protocol export rule: ```text AI cannot approve cultural protocol access. AI cannot remove cultural restrictions. AI cannot downgrade cultural sensitivity. ``` --- ## 20. External work export External works use: ```text uckkarchive_external_work ``` External work export may include: ```text title creator publisher publication year work type language edition identifier citation text rights status reference URL content advisory markers teaching notes when allowed manifest entry ``` External work export must not include unauthorized copies of third-party works. External/foreign media rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` External work package mode: ```text reference_only metadata_only citation_only included_if_licensed redacted omitted ``` --- ## 21. Media source export Media source records use: ```text uckkarchive_media_source ``` Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Media source export rule: ```text Source classification must be exported when it affects reuse, rights, trust, teaching context, download, or export policy. ``` --- ## 22. Restricted integrity export `tool_uckkintegrity` is optional. Ordinary archive/media/content-advisory exports must not require `tool_uckkintegrity`. Integrity-specific export behavior must be hidden, disabled, or fail closed when `tool_uckkintegrity` is absent. Restricted integrity exports may include: ```text restricted archive item metadata proof references media references content advisory flags redacted summaries manifest references integrity export files when authorized ``` Restricted integrity exports must not include: ```text integrity case authority integrity sanctions appeals authority procedure ownership unredacted case records without explicit authority ``` Integrity boundary rule: ```text The archive may preserve integrity-related evidence and restricted summaries. The archive does not own integrity case procedure or decision authority. ``` --- ## 23. Export previews Export preview services must show what will be included before generation. Export preview may show: ```text number of archive items number of media objects number of media files number of media versions number of content markers number of external works number of redacted records number of omitted records estimated package size selected format warnings policy blocks ``` Export preview must not reveal restricted data that the user cannot view. Preview rule: ```text A preview is permission-filtered and policy-filtered. A preview is not a promise that generation will succeed. ``` --- ## 24. Export formats Supported export formats may include: ```text zip json csv html pdf_summary manifest_only ``` Format rule: ```text Format availability depends on export type, policy, files, media rights, content advisories, and redaction level. ``` CSV exports are appropriate for structured metadata. ZIP exports are appropriate for file packages. JSON exports are appropriate for portable structured records. PDF summary exports are appropriate for human-readable summaries. HTML exports are appropriate for browsable packages when policy allows. Manifest-only exports are appropriate for restricted reference packages. --- ## 25. Export redaction levels Canonical export redaction levels: ```text none standard restricted cultural integrity public manifest_only ``` Redaction level meaning: | Level | Meaning | |---|---| | `none` | No redaction beyond normal permission filtering. | | `standard` | Private notes and unsafe metadata are redacted. | | `restricted` | Restricted records are summarized or omitted unless authorized. | | `cultural` | Cultural protocol details are redacted or omitted according to policy. | | `integrity` | Integrity-sensitive details are redacted or omitted according to policy. | | `public` | Export contains only public-safe data. | | `manifest_only` | Export contains metadata/reference manifest only. | Redaction rule: ```text Redaction is part of export construction, not a post-processing decoration. ``` --- ## 26. Export statuses and failure handling Export failures must be explainable to authorized users. Failure reasons may include: ```text permission_denied policy_blocked restricted_content cultural_protocol_block missing_file file_area_error manifest_error storage_error task_error invalid_selection external_work_rights_block privacy_redaction_block ``` Failure handling rule: ```text Failure messages must be useful for troubleshooting without leaking restricted data. ``` --- ## 27. Scheduled export tasks Scheduled export task: ```text classes/task/generate_archive_exports.php ``` Related cleanup task: ```text classes/task/purge_expired_exports.php ``` Optional supporting tasks: ```text classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/rebuild_content_marker_index.php classes/task/rebuild_media_search.php ``` Task rule: ```text Scheduled tasks reuse classes/local domain logic. Scheduled tasks do not bypass policy checks for generated outputs. ``` --- ## 28. Export services Required export-related external services: ```text classes/external/get_export_preview.php classes/external/export_items.php classes/external/export_media.php classes/external/export_collection.php classes/external/get_export_status.php ``` Content advisory and external work services may support export preparation: ```text classes/external/get_content_markers.php classes/external/get_content_tags.php classes/external/get_content_tag_sets.php classes/external/get_external_works.php classes/external/get_external_work.php ``` Service rule: ```text Export services must validate parameters, resolve context, check capabilities, apply policy, filter restricted data, and return only authorized information. ``` --- ## 29. Export UI Export UI may include: ```text export form export preview selected item summary selected media summary redaction summary content advisory warning summary cultural protocol warning summary external work reference summary format selector export status panel download button failure message panel ``` Relevant form: ```text classes/form/export_form.php ``` Relevant output classes: ```text classes/output/content_advisory_panel.php classes/output/media_card.php classes/output/media_collection.php classes/output/provenance_panel.php ``` Relevant template areas: ```text templates/content_advisory_panel.mustache templates/media_card.mustache templates/media_collection.mustache templates/provenance_panel.mustache ``` Relevant AMD module: ```text amd/src/export.js ``` UI rule: ```text The UI displays policy-filtered export information. The UI does not decide export authority. ``` --- ## 30. Export event model Export-related events include: ```text classes/event/archive_item_exported.php classes/event/media_exported.php ``` Export events should record: ```text context id export id export uuid export type actor user id object id when applicable object uuid when applicable created time ``` Export events must not expose: ```text raw file content private notes restricted metadata private cultural protocol notes integrity-sensitive details redacted data ``` Event rule: ```text Events audit successful state changes. Events are not export manifests. ``` --- ## 31. Privacy and exports Exports may contain personal data. Privacy-sensitive export data includes: ```text archive item authorship media submitter metadata reviewer metadata validator metadata revision actors content marker creators content reviewers external work notes restricted notes private review notes cultural protocol notes export actor metadata export manifest metadata ``` Privacy rule: ```text A user may receive their own personal data through Moodle Privacy API. A user must not receive restricted cultural, integrity, third-party, or other user data merely because it is stored near their record. ``` Privacy provider must account for export records and export files. --- ## 32. Backup and restore of exports Backup may include export metadata when appropriate. Backup may include export files when policy and backup settings allow. Restore must preserve or reconstruct: ```text export records export status where appropriate manifest references file references redaction metadata actor references where possible archive item mappings media mappings content marker mappings external work mappings ``` Restore rule: ```text Restored export packages must not become more accessible than they were before backup. ``` --- ## 33. Retention and expiry Export packages must support retention rules. Retention controls: ```text how long export files remain downloadable when export package files expire when manifests remain as audit records when files are purged when metadata is retained when soft-deleted exports are hidden ``` Retention rule: ```text Export files may expire before export metadata is deleted. ``` Expired exports must not be downloadable. Revoked exports must not be downloadable. Soft-deleted exports must not appear in normal export lists. --- ## 34. Report plugin integration `mod_uckkarchive` may expose safe data for `report_uckk`. Safe integration may include: ```text summary counts archive item counts media counts validation state counts content advisory counts restricted record counts export counts redaction counts course-level summary data program-level summary data when authorized ``` `report_uckk` may use this data for institutional dashboards. Integration rule: ```text report_uckk may report on archive data. report_uckk does not own archive records. mod_uckkarchive does not become report_uckk. ``` --- ## 35. Reporting-safe fields Reporting-safe fields may include: ```text archive id course id context id item count media count validated count restricted count content marker count external work count export count last activity time status counts validation counts media type counts redaction counts ``` Reporting-safe fields must not include: ```text raw restricted content private notes cultural protocol private details integrity case details unauthorized personal data unredacted external work notes ``` Reporting rule: ```text Aggregated reporting must still respect privacy, cultural protocol, and institutional authority boundaries. ``` --- ## 36. Export package structure A ZIP export package should use a predictable structure. Recommended package layout: ```text manifest.json README.txt items/ media/ media/originals/ media/derivatives/ media/previews/ media/thumbnails/ media/captions/ media/transcripts/ proofs/ kristals/ provenance/ revisions/ content_advisories/ external_works/ redactions/ ``` Package layout rule: ```text Package structure must match the manifest. The manifest is the authoritative index. ``` --- ## 37. External work locator examples External work exports may include locators without including the external work itself. Examples: ```text Movie Maïna -> sexual_violence -> 01:12:30-01:15:10 Book The Body Keeps the Score -> sexual_violence -> page 42-45 PDF -> culturally_sensitive -> page 7 Audio -> grief_or_mourning -> 00:08:12-00:09:40 Website -> colonial_violence -> url_fragment #section-3 ``` Locator rule: ```text Locators make advisories useful without requiring unauthorized storage or export of third-party content. ``` --- ## 38. Export manifest object model Each manifest object should include: ```text object_type object_id object_uuid included redaction_state visibility restricted_flags source_classification validation_state provenance_state file_entries relations content_advisories external_references ``` Each file entry should include: ```text file_area item_id filename mime_type size content_hash included redaction_state source_media_uuid source_media_version_uuid ``` Each content advisory entry should include: ```text content_marker_uuid tag_key tag_set_key locator_type locator_start locator_end severity audience_suitability review_state cultural_protocol_flag included redaction_state ``` --- ## 39. Export security rules Export generation must enforce: ```text context validation capability validation sesskey validation for web actions parameter validation record ownership checks media status checks visibility checks download checks export checks content advisory checks cultural protocol checks retention checks redaction checks ``` Export download must re-check: ```text context capability export ownership or authority export status expiry revocation file availability policy state ``` Security rule: ```text Export authorization is checked at request time, generation time, and download time. ``` --- ## 40. Testing requirements Testing must cover: ```text archive item export media item export media collection export content advisory export external work reference export restricted export redacted export manifest generation manifest redaction export preview filtering export service permissions export file-area storage export download authorization expired export blocking revoked export blocking backup/restore of export metadata privacy coverage for export records reporting boundary with report_uckk ``` Required tests include: ```text tests/export_test.php tests/media_library_test.php tests/content_advisory_test.php tests/external_work_test.php tests/privacy_provider_test.php tests/services_test.php tests/backup_restore_test.php ``` Testing rule: ```text Tests verify final target behavior. Tests must not depend on historical gap documents. Tests must not require mod/uckkarchive:versionitem. ``` --- ## 41. Non-negotiable export rules ```text mod_uckkarchive owns archive/media export packages. report_uckk owns institutional reports. Exports are permission-filtered. Exports are policy-filtered. Exports are redaction-aware. Exports are manifest-backed. Exports are File API-backed. Exports do not bypass visibility. Exports do not bypass cultural protocol restrictions. Exports do not bypass content advisory policy. Exports do not imply ownership over external works. Exports do not include unauthorized third-party content. Exports do not expose private review notes. Exports do not expose restricted integrity details without authority. A ready export still requires authorization before download. ``` --- ## 42. Final rule ```text This document defines the final target behavior for reporting boundaries, archive/media exports, content advisory exports, external work references, manifests, redaction, retention, and package portability. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ``` ================================================================================================ FILE: mod/uckkarchive/docs/21_testing_strategy.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 85602745cf4cb2462de2f35121beaf900b0a1cf17dc14f54eb3dd5209c82feb2 CONTENT_BYTES: 24825 ================================================================================================ # 21 — Testing Strategy **Path:** `docs/21_testing_strategy.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Test strategy for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Purpose This document defines the final testing strategy for `mod_uckkarchive`. `mod_uckkarchive` is a Moodle-native activity module with a self-contained archive, media library, and content advisory system. The test suite must prove that the module behaves correctly as: ```text archive memory engine media library engine content advisory governance engine Moodle activity module File API consumer Privacy API provider Backup/restore participant External services provider UI-rendered Moodle module ``` Testing must verify final target behavior. Testing must not depend on historical gap documents, acceptance checklists, or release notes. --- ## 2. Core testing principle Canonical rule: ```text Tests verify implemented behavior against final-state specifications. Tests do not document historical transitions. Tests do not preserve obsolete architecture. ``` All tests must align with: ```text docs/_alignment_variables.md docs/01_architecture_decision.md docs/02_domain_boundaries.md docs/03_file_architecture.md docs/04_data_model.md docs/05_media_library.md docs/06_file_api_and_storage.md docs/07_permissions_and_roles.md docs/08_archive_workflows.md docs/09_media_workflows.md docs/10_provenance_versioning_validation.md docs/11_privacy_retention_redaction.md docs/12_backup_restore.md docs/13_services_and_ajax_api.md docs/14_events_and_audit.md docs/15_ui_templates_and_amd.md docs/16_integration_with_courses.md docs/17_integration_with_challenges.md docs/18_integration_with_assemblies.md docs/19_integration_with_integrity.md docs/20_reporting_and_exports.md docs/22_installation.md docs/23_upgrade.md docs/24_release_spec.md ``` --- ## 3. Required test files Canonical test files: ```text tests/archive_test.php tests/backup_restore_test.php tests/content_advisory_test.php tests/export_test.php tests/external_work_test.php tests/file_api_test.php tests/lib_test.php tests/media_library_test.php tests/privacy_provider_test.php tests/services_test.php tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` Optional future expansion may split large files by subsystem, but these files define the required baseline. --- ## 4. Testing layers The test suite must cover these layers: ```text unit/domain tests database tests File API tests policy tests external service tests privacy provider tests backup/restore tests export/manifest tests event/audit tests scheduled task tests renderer/output tests Behat UI tests upgrade tests ``` Each layer tests a different responsibility. No layer should duplicate all behavior from another layer. --- ## 5. Archive tests File: ```text tests/archive_test.php ``` Archive tests must cover: ```text activity instance creation archive item creation archive item draft state archive item submitted state archive item validated state archive item restricted state archive item contested state archive item invalidated state archive item archived state archive item visibility filtering archive item revision archive item provenance archive item proof linkage archive item Kristal linkage archive item export eligibility archive item redaction eligibility ``` Archive tests must verify canonical statuses: ```text draft submitted under_review validated published restricted contested invalidated superseded archived ``` Archive tests must verify canonical validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Archive tests must verify that: ```text AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. ``` --- ## 6. Media library tests File: ```text tests/media_library_test.php ``` Media library tests must cover: ```text media object creation media uuid generation media source metadata media version creation media version inheritance media original file registration media preview file registration media thumbnail file registration media derivative file registration media caption file registration media transcript file registration media attachment file registration media visibility filtering media lifecycle transitions media soft deletion media relation creation media collection creation media collection membership media tag assignment media search indexing behavior media export eligibility restricted media behavior culturally restricted media behavior ``` Media tests must verify canonical media states: ```text draft submitted active restricted superseded archived deleted_soft ``` Media tests must verify that file existence does not equal media availability. Media status, visibility, policy, and retention must control usability. --- ## 7. Content advisory tests File: ```text tests/content_advisory_test.php ``` Content advisory tests must cover: ```text content tag creation content tag set creation content marker creation content marker locator validation content marker review content review state transitions content advisory visibility audience suitability behavior cultural protocol behavior restricted cultural access advisory acknowledgement behavior content marker relation to media content marker relation to media version content marker relation to archive item content marker relation to external work content marker redaction behavior ``` Content advisory tests must verify required tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Content advisory tests must verify canonical review states: ```text draft pending_review reviewed approved contested retired ``` Content advisory tests must verify canonical severity values: ```text notice moderate strong restricted ``` Content advisory tests must verify that a content advisory does not automatically ban media. It must define conditions for responsible access, warning, review, restriction, teaching, or contextualization. --- ## 8. External work tests File: ```text tests/external_work_test.php ``` External work tests must cover: ```text external work creation external work metadata validation external work type validation external source ownership validation external rights metadata external locator metadata external work advisory markers foreign media reference behavior reference-only external media licensed external media public domain external media fair-use reference behavior restricted reference behavior export of external work metadata redaction of restricted external work notes ``` External work tests must verify supported external work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External work tests must verify that the archive does not imply ownership over third-party works. --- ## 9. File API tests File: ```text tests/file_api_test.php ``` File API tests must cover: ```text pluginfile access context resolution file area registry item file access proof file access Kristal file access provenance file access validation file access revision file access export package access export manifest access media original access media preview access media thumbnail access media derivative access media caption access media transcript access media attachment access content review file access external work reference file access cultural protocol file access restricted file denial redacted file denial deleted_soft media file denial ``` Canonical component: ```text mod_uckkarchive ``` Canonical archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Canonical content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File API tests must verify: ```text No production archive/media files are served from unmanaged public folders. No binary media files are stored directly in custom database fields. File URL possession is not authority. ``` --- ## 10. Permission and policy tests Permission tests may live in: ```text tests/archive_test.php tests/media_library_test.php tests/content_advisory_test.php tests/services_test.php tests/file_api_test.php ``` Policy tests must verify that Moodle capabilities are gates, not final authority. Policy classes: ```text classes/local/archive_policy.php classes/local/media_policy.php classes/local/content_policy.php ``` Policy tests must cover: ```text view archive add archive item revise archive item validate archive item export archive item view media add media edit media delete media download media version media export media manage media collections view advisories manage advisories review advisories view culturally restricted material manage external works ``` Policy tests must verify that templates, AMD, forms, and controllers do not authorize access. Server-side policy must filter before rendering or service return. --- ## 11. Capability tests Capability tests must verify canonical archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Capability tests must verify canonical media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Capability tests must verify canonical content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Capability tests must verify that the module does not use: ```text mod/uckkarchive:versionitem ``` --- ## 12. External service tests File: ```text tests/services_test.php ``` Service tests must cover: ```text parameter validation context resolution login requirement capability checks policy checks record existence record visibility return value filtering warning generation exception behavior state-changing service events restricted data denial redacted data denial ``` Service tests must cover archive services, media services, content advisory services, external work services, and export services. Services must not return restricted data for client-side hiding. Filtering must happen server-side. --- ## 13. Privacy provider tests File: ```text tests/privacy_provider_test.php ``` Privacy tests must cover: ```text archive item user data proof user data Kristal user data provenance user data revision user data export user data media object user data media version user data media source user data media collection user data media relation user data media tag user data content tag user data content marker user data content review user data external work curator data restricted metadata cultural protocol notes content advisory notes file references ``` Privacy tests must verify: ```text privacy export privacy deletion privacy redaction retention-aware deletion restricted data handling third-party data handling institutional preservation behavior ``` A privacy request must not automatically bypass archive, media, content, retention, or cultural protocol policy. --- ## 14. Backup and restore tests File: ```text tests/backup_restore_test.php ``` Backup/restore tests must verify preservation of: ```text archive records archive items proof records Kristals provenance records revision records export records media records media versions media relations media tags media collections media collection membership content tags content tag sets content markers content reviews external works media source records file areas visibility restricted flags cultural protocol flags audience suitability validation state redaction state retention class UUIDs source references export manifests ``` Restore tests must verify: ```text ID mapping file restoration media relation restoration collection restoration external work restoration content marker restoration restricted state preservation cultural protocol preservation privacy-sensitive data preservation according to policy ``` Restore must not create: ```text grades challenge attempts Assembly decisions integrity cases institutional reports external authority records ``` --- ## 15. Export and manifest tests File: ```text tests/export_test.php ``` Export tests must cover: ```text archive item export selected archive export media export media collection export restricted export denial redacted export content advisory manifest inclusion external work metadata export file hash generation manifest generation export package creation export package access export retention export status services ``` Canonical manifest filename: ```text manifest.json ``` Manifest tests must verify inclusion of: ```text plugin component archive id export id export timestamp export actor export reason archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Exports must not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. --- ## 16. Event and audit tests Event tests must cover events such as: ```text archive_viewed archive_item_created archive_item_validated archive_item_revised archive_item_exported media_created media_updated media_version_created media_collection_created media_exported content_marker_created content_marker_reviewed external_work_created ``` Event tests must verify: ```text correct context correct object id correct related user id when applicable correct other data when applicable no raw restricted content in event payload no private cultural protocol notes in event payload no redacted data in event payload ``` Events audit successful state changes. Events must not leak sensitive content. --- ## 17. Scheduled task tests Scheduled task tests may live in subsystem test files. Tasks to test: ```text classes/task/generate_archive_exports.php classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/purge_expired_exports.php classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php classes/task/validate_pending_items.php ``` Task tests must verify: ```text task registration task execution idempotency where required policy-safe output failure handling restricted data handling file creation through Moodle File API no bypass of domain policy ``` Scheduled tasks reuse `classes/local` domain logic. --- ## 18. Renderer and output tests Renderer/output tests must verify renderable payloads for: ```text archive item card archive view Kristal card media card media collection media library media version list content advisory panel external work card provenance panel validation panel ``` Output tests must verify: ```text permission-filtered fields redacted fields restricted badges content advisory badges cultural protocol badges download flags export flags review flags no hidden raw restricted payload ``` Output classes format permission-filtered data. Output classes do not authorize access. --- ## 19. Behat UI tests Required Behat files: ```text tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` ### 19.1 Archive Behat coverage Archive UI tests must cover: ```text teacher creates archive activity participant views archive activity participant submits archive item mentor revises archive item archivist validates archive item restricted archive item is hidden from unauthorized user validated archive item appears to authorized user archive item export action is visible only when allowed ``` ### 19.2 Media Behat coverage Media UI tests must cover: ```text authorized user opens media library authorized user adds media authorized user edits media metadata authorized user adds media version authorized user creates media collection authorized user adds media to collection unauthorized user cannot download media original restricted media thumbnail is hidden or redacted deleted_soft media is not shown as active ``` ### 19.3 Content advisory Behat coverage Content advisory UI tests must cover: ```text authorized user creates content marker authorized user adds advisory tag authorized reviewer reviews advisory content advisory badge appears where permitted cultural protocol badge appears where permitted unauthorized user cannot view culturally restricted details external work is referenced without implying ownership advisory acknowledgement appears where required ``` Behat tests must focus on user-visible behavior. Policy depth belongs in PHPUnit tests. --- ## 20. Upgrade tests Upgrade tests must verify schema migration in: ```text db/upgrade.php ``` Upgrade tests must cover: ```text new archive fields new media tables new media version tables new media relation tables new media tag tables new media collection tables new content advisory tables new external work tables new source fields new uuid fields new visibility values new file area normalization capability additions removed versionitem capability absence ``` Upgrade must preserve existing archive data. Upgrade must not create invalid permissions. Upgrade must not expose restricted data. --- ## 21. Installation tests Installation tests must verify: ```text db/install.xml creates all required tables db/access.php defines all required capabilities db/services.php defines all required services db/events.php registers required observers db/tasks.php registers required tasks version.php has correct component metadata tool_uckkintegrity is not a hard dependency local_uckk dependency is handled according to plugin architecture ``` Installation must not require raw public folders for media storage. --- ## 22. Integration tests Integration tests must verify boundaries with: ```text Moodle course context Moodle gradebook local_uckk mod_uckkchallenge mod_uckkassembly tool_uckkintegrity report_uckk ``` Boundary tests must verify: ```text archive can reference external domains archive does not own external authority archive does not create grades archive does not create challenge workflow state archive does not create Assembly decisions archive does not create integrity cases archive does not create institutional reports ``` Optional integrations must fail closed when absent. --- ## 23. Search and listing tests Search/listing tests must verify: ```text archive search filtering media search filtering content marker search filtering external work search filtering collection listing filtering tag facet filtering advisory facet filtering restricted count protection autocomplete protection thumbnail protection preview protection snippet protection ``` Search must not leak restricted records through: ```text title snippet thumbnail preview caption transcript tag collection membership content advisory marker external work reference count facet autocomplete ``` --- ## 24. Redaction tests Redaction tests must verify: ```text restricted archive fields redacted restricted media metadata redacted restricted thumbnails hidden or replaced restricted previews hidden or replaced cultural protocol notes redacted private review notes redacted external work restricted notes redacted manifest redaction privacy export redaction service response redaction UI payload redaction ``` Redaction must be enforced server-side. --- ## 25. Negative tests The suite must include negative tests for: ```text unauthenticated access missing capability wrong course context wrong archive instance wrong media id wrong media uuid restricted record without permission culturally restricted record without permission download without download capability export without export capability review without review capability invalid locator invalid source ownership invalid visibility value invalid media state transition invalid validation transition invalid relation type invalid file area deleted_soft media access ``` Negative tests are required for trust. --- ## 26. Test data builders The module should use test data helpers for: ```text archive instance archive item proof Kristal provenance record revision record media object media version media relation media tag media collection media collection item content tag content tag set content marker content review external work media source export package ``` Builders must create valid objects by default. Invalid test objects should be explicit. --- ## 27. Fixture principles Fixtures must be: ```text minimal explicit policy-aware context-aware repeatable isolated ``` Fixtures must avoid: ```text global state pollution hardcoded unrelated users unmanaged files public folder media hidden dependencies on optional plugins ``` --- ## 28. Performance and scale tests The test suite should include reasonable scale checks for: ```text archive item listing media listing media search content marker search collection membership export manifest generation backup structure generation privacy metadata export ``` Scale tests should verify that permission filtering remains correct under larger datasets. --- ## 29. Security tests Security tests must cover: ```text capability enforcement context isolation file access enforcement external service access restricted data filtering redaction content advisory restriction cultural protocol restriction export restriction CSRF/session behavior where applicable input validation parameter validation ``` Security tests must verify that client-side hiding is never the only protection. --- ## 30. Test ownership map | Area | Primary test file | |---|---| | Archive domain | `tests/archive_test.php` | | Media domain | `tests/media_library_test.php` | | Content advisories | `tests/content_advisory_test.php` | | External works | `tests/external_work_test.php` | | File API | `tests/file_api_test.php` | | Services | `tests/services_test.php` | | Privacy | `tests/privacy_provider_test.php` | | Backup/restore | `tests/backup_restore_test.php` | | Exports/manifests | `tests/export_test.php` | | Moodle callbacks | `tests/lib_test.php` | | Archive UI | `tests/behat/uckkarchive.feature` | | Media UI | `tests/behat/uckkarchive_media.feature` | | Content advisory UI | `tests/behat/uckkarchive_content_advisory.feature` | --- ## 31. Required test assertions Every relevant test should assert: ```text record exists record belongs to correct context record uses correct component record has correct status record has correct visibility record has correct uuid record has correct provenance record is permission-filtered record is redacted when required record is exported only when permitted record is restored correctly record does not leak restricted data ``` --- ## 32. Final testing rule ```text The test suite must prove that mod_uckkarchive works as a self-contained archive, media library, and content advisory system inside Moodle. It must prove that the module owns archive/media/content records while using Moodle for context, users, roles, capabilities, File API, Privacy API, Backup/Restore API, events, services, settings, rendering, and scheduled tasks. It must prove that restricted, culturally sensitive, external, redacted, private, and retention-controlled records remain protected across UI, services, files, exports, backup, restore, privacy, and search. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/22_installation.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 0db8832e13aaafeb58ae9302fb13942613fb33af0d43305519bb726679a5dae3 CONTENT_BYTES: 27476 ================================================================================================ # 22 — Installation **Path:** `docs/22_installation.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Installation, deployment, upgrade preparation, runtime requirements, packaging, and verification for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Purpose This document defines the final installation contract for `mod_uckkarchive`. `mod_uckkarchive` is a Moodle-native activity module with a self-contained archive, media library, and content advisory system. Canonical architecture: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` Installation must place the plugin inside Moodle as a standard activity module while preserving the module’s internal ownership of: ```text archive records archive items media records media versions media collections media relations media tags content advisory tags content tag sets content markers content reviews external works media source records proofs Kristals provenance revisions validation state restricted metadata export packages export manifests ``` --- ## 2. Canonical paths Source of truth path: ```text C:\mycode\UCKK\uckk-moodle\mod\uckkarchive ``` Active Moodle plugin path: ```text C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive ``` Canonical Moodle relative path: ```text mod/uckkarchive ``` Documentation path: ```text C:\mycode\UCKK\uckk-moodle\mod\uckkarchive\docs ``` Active Moodle documentation mirror: ```text C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive\docs ``` The plugin must not be installed at: ```text local/uckkarchive blocks/uckkarchive admin/tool/uckkarchive report/uckkarchive mod/mod_uckkarchive ``` Correct plugin folder: ```text uckkarchive ``` Correct component name: ```text mod_uckkarchive ``` --- ## 3. Installation target The final installed tree must be: ```text moodle/public/mod/uckkarchive/ ├── add.php ├── export.php ├── index.php ├── item.php ├── lib.php ├── locallib.php ├── media.php ├── mod_form.php ├── settings.php ├── styles.css ├── validate.php ├── version.php ├── view.php ├── amd/ ├── backup/ ├── classes/ ├── db/ ├── docs/ ├── lang/ ├── pix/ ├── templates/ └── tests/ ``` The plugin is installed when Moodle detects: ```text mod/uckkarchive/version.php ``` and the component declared in code is: ```text mod_uckkarchive ``` --- ## 4. Installation mode The plugin may be installed by either: ```text copy deployment git checkout / pull package extraction ``` The installed folder must contain the clean release package only. Do not install generated codedump files, scratch files, backup files, temporary files, or process documents. Forbidden install artifacts: ```text *.bak *.tmp *.orig *.rej *.patch *.log .DS_Store Thumbs.db node_modules/ codedump files AI scratch files runtime export files outside Moodle File API ``` --- ## 5. Required top-level files The installation package must include: ```text add.php export.php index.php item.php lib.php locallib.php media.php mod_form.php settings.php styles.css validate.php version.php view.php ``` Root files are request controllers or Moodle callback files. Business logic must remain in: ```text classes/local ``` External services must remain in: ```text classes/external ``` Renderable data must remain in: ```text classes/output ``` Mustache templates must remain in: ```text templates ``` AMD source and build files must remain in: ```text amd ``` --- ## 6. Required database files The installation package must include: ```text db/access.php db/events.php db/install.xml db/services.php db/tasks.php db/upgrade.php ``` Database file roles: | File | Required role | |---|---| | `db/access.php` | Defines archive, media, and content advisory capabilities. | | `db/events.php` | Registers observers. | | `db/install.xml` | Defines the full install schema for new installations. | | `db/services.php` | Defines Moodle external services. | | `db/tasks.php` | Defines scheduled tasks. | | `db/upgrade.php` | Migrates existing installations to the current schema. | New installations use: ```text db/install.xml ``` Existing installations use: ```text db/upgrade.php ``` --- ## 7. Required database schema New installation must create archive tables: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export ``` New installation must create media library tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` New installation must create content advisory and external-work tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Identifier rule: ```text id = local Moodle database primary key uuid = stable portable object identity ``` UUIDs must be available for: ```text archive items media objects media versions media collections content markers external works export packages ``` --- ## 8. Required capabilities Installation must register archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Installation must register media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Installation must register content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Do not register this removed capability: ```text mod/uckkarchive:versionitem ``` Archive item revision uses: ```text mod/uckkarchive:reviseitem ``` Media versioning uses: ```text mod/uckkarchive:versionmedia ``` --- ## 9. Required local classes Installation must include archive local classes: ```text classes/local/archive_item.php classes/local/archive_policy.php classes/local/export_package.php classes/local/kristal.php classes/local/proof.php classes/local/provenance.php classes/local/revision.php ``` Installation must include media local classes: ```text classes/local/media.php classes/local/media_collection.php classes/local/media_file.php classes/local/media_policy.php classes/local/media_relation.php classes/local/media_search.php classes/local/media_source.php classes/local/media_tag.php classes/local/media_version.php ``` Installation must include content advisory local classes: ```text classes/local/content_marker.php classes/local/content_policy.php classes/local/content_review.php classes/local/content_tag.php classes/local/content_tag_set.php classes/local/external_work.php ``` Installation must include shared local infrastructure: ```text classes/local/context_resolver.php classes/local/file_area_registry.php classes/local/manifest_builder.php classes/local/metadata_validator.php classes/local/uuid.php ``` `classes/local` is the authority layer for archive, media, and content advisory behavior. --- ## 10. Required external service classes Installation must include archive service classes: ```text classes/external/get_archive.php classes/external/get_archive_items.php classes/external/get_archive_item.php classes/external/get_archive_item_card.php classes/external/get_proofs.php classes/external/get_provenance_panel.php classes/external/get_kristal.php classes/external/get_revisions.php classes/external/get_restricted_item.php classes/external/save_item_draft.php classes/external/add_item.php classes/external/add_proof.php classes/external/update_provenance.php classes/external/validate_item.php classes/external/revise_item.php classes/external/create_kristal.php classes/external/update_kristal.php ``` Installation must include media service classes: ```text classes/external/get_media.php classes/external/get_media_item.php classes/external/get_media_card.php classes/external/search_media.php classes/external/add_media.php classes/external/update_media.php classes/external/delete_media.php classes/external/add_media_version.php classes/external/get_media_versions.php classes/external/get_media_relations.php classes/external/add_media_relation.php classes/external/remove_media_relation.php classes/external/get_media_collections.php classes/external/get_media_collection.php classes/external/add_media_collection.php classes/external/update_media_collection.php classes/external/add_media_to_collection.php classes/external/remove_media_from_collection.php classes/external/tag_media.php classes/external/untag_media.php ``` Installation must include content advisory and external-work service classes: ```text classes/external/get_content_tags.php classes/external/get_content_tag_sets.php classes/external/get_content_markers.php classes/external/add_content_marker.php classes/external/update_content_marker.php classes/external/delete_content_marker.php classes/external/review_content_marker.php classes/external/get_external_works.php classes/external/get_external_work.php classes/external/add_external_work.php classes/external/update_external_work.php ``` Installation must include export service classes: ```text classes/external/get_export_preview.php classes/external/export_items.php classes/external/export_media.php classes/external/export_collection.php classes/external/get_export_status.php ``` Every external service must resolve context, check capabilities, call policy classes, and return permission-filtered data. --- ## 11. Required forms Installation must include: ```text classes/form/archive_item_form.php classes/form/content_marker_form.php classes/form/content_review_form.php classes/form/content_tag_form.php classes/form/export_form.php classes/form/external_work_form.php classes/form/kristal_form.php classes/form/media_collection_form.php classes/form/media_form.php classes/form/media_relation_form.php classes/form/media_version_form.php classes/form/validation_form.php ``` Forms collect and shape input. Forms do not replace policy classes. --- ## 12. Required output classes Installation must include: ```text classes/output/archive_item_card.php classes/output/archive_view.php classes/output/content_advisory_panel.php classes/output/external_work_card.php classes/output/kristal_card.php classes/output/media_card.php classes/output/media_collection.php classes/output/media_library.php classes/output/media_version_list.php classes/output/provenance_panel.php classes/output/renderer.php ``` Output classes format permission-filtered data. Output classes do not authorize access. --- ## 13. Required templates Installation must include: ```text templates/archive_item_card.mustache templates/archive_view.mustache templates/content_advisory_panel.mustache templates/external_work_card.mustache templates/kristal_card.mustache templates/media_card.mustache templates/media_collection.mustache templates/media_library.mustache templates/media_relation_list.mustache templates/media_upload.mustache templates/media_version_list.mustache templates/proof_card.mustache templates/provenance_panel.mustache templates/validation_panel.mustache ``` Templates receive pre-filtered render data. Templates do not enforce authority. --- ## 14. Required AMD files Installation must include AMD source files: ```text amd/src/archive.js amd/src/content_advisory.js amd/src/export.js amd/src/external_work.js amd/src/kristal.js amd/src/media.js amd/src/media_collection.js ``` Runtime package must include AMD build files: ```text amd/build/archive.min.js amd/build/content_advisory.min.js amd/build/export.min.js amd/build/external_work.min.js amd/build/kristal.min.js amd/build/media.min.js amd/build/media_collection.min.js ``` AMD rule: ```text amd/src is source. amd/build is generated. AMD modules do not authorize access. ``` After changing AMD source files, rebuild Moodle AMD assets before packaging. --- ## 15. Required backup and restore files Installation must include: ```text backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` Backup/restore must cover archive-owned records: ```text archive items proofs Kristals provenance revisions exports media objects media versions media relations media tags media collections media collection items content tags content tag sets content markers content reviews external works media source records File API files ``` Restore must not create external authority: ```text grades transcripts course enrolment authority Assembly authority challenge workflow authority integrity case authority institutional reporting authority ``` --- ## 16. Required events and tasks Installation must include event classes: ```text classes/event/archive_viewed.php classes/event/archive_item_created.php classes/event/archive_item_validated.php classes/event/archive_item_revised.php classes/event/archive_item_exported.php classes/event/media_created.php classes/event/media_updated.php classes/event/media_version_created.php classes/event/media_collection_created.php classes/event/media_exported.php classes/event/content_marker_created.php classes/event/content_marker_reviewed.php classes/event/external_work_created.php ``` Installation must include scheduled task classes: ```text classes/task/generate_archive_exports.php classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/purge_expired_exports.php classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php classes/task/validate_pending_items.php ``` Scheduled task declarations belong in: ```text db/tasks.php ``` --- ## 17. Required language files Installation must include: ```text lang/en/uckkarchive.php lang/fr/uckkarchive.php ``` Language files must contain matching keys for: ```text plugin identity capabilities settings forms services events archive UI media UI content advisory UI external work UI collections relations versions validation privacy backup/restore errors warnings access messages ``` Do not ship backup language files: ```text lang/en/uckkarchive.php.bak_20260522_124454 ``` Do not ship any `*.bak` language files. --- ## 18. Required visual assets Installation must include: ```text pix/icon.svg ``` Optional visual assets: ```text pix/media.svg pix/collection.svg ``` User-uploaded media must not be stored in: ```text pix ``` `pix` is for static plugin interface assets only. --- ## 19. Moodle File API requirement The plugin must store files through Moodle File API. Component: ```text mod_uckkarchive ``` Required archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Required media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Required content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File-area registry: ```text classes/local/file_area_registry.php ``` Installation is incomplete if file areas are hard-coded inconsistently across callbacks, services, backup, restore, privacy, tests, and pluginfile handling. --- ## 20. Optional integration dependencies The archive may integrate with: ```text local_uckk mod_uckkchallenge mod_uckkassembly tool_uckkintegrity report_uckk ``` Ordinary archive, media, and content advisory operation must not require optional integrations. Integration rule: ```text optional integration absent = hide, disable, or fail closed for integration-specific features ordinary archive/media/content-advisory features continue ``` `tool_uckkintegrity` is optional. Integrity-specific features must not break ordinary installation when `tool_uckkintegrity` is absent. --- ## 21. Installation procedure — copy deployment Copy the clean plugin folder into Moodle: ```text from: C:\mycode\UCKK\uckk-moodle\mod\uckkarchive to: C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive ``` Then run Moodle upgrade using one of: ```text Site administration → Notifications ``` or CLI: ```text php admin/cli/upgrade.php ``` After upgrade, purge caches: ```text php admin/cli/purge_caches.php ``` Then verify that the plugin appears as an activity module. --- ## 22. Installation procedure — development mirror During development, the repository source of truth remains: ```text C:\mycode\UCKK\uckk-moodle\mod\uckkarchive ``` The active Moodle copy remains: ```text C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive ``` Development mirror rule: ```text Generate or edit source files in the source plugin path. Mirror the plugin into the active Moodle path for runtime testing. Do not manually edit generated AMD build files except through the Moodle AMD build process. ``` Documentation mirror rule: ```text Source docs live in the source plugin docs folder. Active Moodle docs may be mirrored for local reference. ``` --- ## 23. Installation procedure — new Moodle site For a new Moodle site: ```text copy mod/uckkarchive into Moodle mod directory confirm version.php component = mod_uckkarchive confirm db/install.xml includes all target tables confirm amd/build files exist run Moodle upgrade purge caches assign capabilities to roles create a course add UCKK Archive activity verify archive view verify media library view verify content advisory panel verify backup/restore availability ``` New site installation uses: ```text db/install.xml ``` --- ## 24. Installation procedure — existing Moodle site For an existing Moodle site: ```text back up Moodle database back up moodledata copy updated plugin files confirm version.php version bump run Moodle upgrade verify db/upgrade.php completed purge caches verify capabilities verify services verify scheduled tasks verify backup/restore verify privacy provider verify archive item access verify media library access verify content advisory access ``` Existing site installation uses: ```text db/upgrade.php ``` Upgrade must migrate existing archive data without silently losing: ```text archive items files provenance validation state revisions exports visibility restricted status ``` --- ## 25. Post-install verification After installation, verify Moodle detects the plugin: ```text Site administration → Plugins → Activity modules → UCKK Archive ``` Verify activity creation: ```text course → turn editing on → add activity or resource → UCKK Archive ``` Verify root pages: ```text view.php index.php add.php item.php media.php export.php validate.php ``` Verify that access is controlled by Moodle login and capabilities. --- ## 26. Database verification Verify these table groups exist: ```text archive tables media tables content advisory tables external work tables ``` Minimum table verification: ```text uckkarchive uckkarchive_item uckkarchive_media uckkarchive_media_version uckkarchive_media_collection uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Verify UUID fields exist where required. Verify indexes exist for: ```text context lookups archive id lookups media id lookups uuid lookups status filtering visibility filtering source references content marker locators external work references ``` --- ## 27. Capability verification Verify role permissions for: ```text student teacher editingteacher manager ``` Minimum role expectations: ```text students may view permitted archive/media records teachers may create and manage course-level archive/media records reviewers may validate archive records where assigned managers may administer restricted archive/media records culturally restricted material requires explicit authority external work management requires explicit authority ``` Do not grant culturally restricted access through ordinary media viewing alone. Do not grant restricted integrity access through ordinary archive viewing alone. --- ## 28. Service verification Verify service declarations in: ```text db/services.php ``` Service verification includes: ```text archive item services media services media collection services content advisory services external work services export services ``` Every service must: ```text require login resolve Moodle context validate parameters check capabilities call policy classes return permission-filtered data avoid leaking restricted metadata ``` --- ## 29. Backup/restore verification Verify backup includes: ```text archive items media objects media versions media collections content markers content reviews external works media source records File API files ``` Verify restore preserves: ```text uuid identity visibility restriction state content advisory state cultural protocol state validation state provenance revision history relations collections export metadata ``` Verify restore does not create: ```text grades transcripts Assembly authority challenge workflow authority integrity case authority institutional report authority ``` --- ## 30. Privacy verification Verify Moodle privacy subsystem recognizes: ```text classes/privacy/provider.php ``` Privacy provider must cover user-linked data in: ```text archive items proofs Kristals provenance revisions exports media objects media versions media relations media collections media tags content tags content tag sets content markers content reviews external works where user-linked media source records where user-linked files ``` Privacy behavior must respect: ```text retention redaction restricted access cultural protocol institutional memory legal/ethical preservation needs ``` --- ## 31. AMD and cache verification After installing or updating AMD files: ```text build AMD modules purge Moodle caches reload pages using browser cache bypass ``` Verify runtime AMD modules are available for: ```text archive UI media UI media collection UI content advisory UI external work UI export UI Kristal UI ``` Required build files: ```text amd/build/archive.min.js amd/build/content_advisory.min.js amd/build/export.min.js amd/build/external_work.min.js amd/build/kristal.min.js amd/build/media.min.js amd/build/media_collection.min.js ``` --- ## 32. File access verification Verify `lib.php` pluginfile handling supports registered file areas. File access verification must confirm: ```text users cannot access files without context permission restricted files are not leaked culturally restricted files require explicit permission integrity-restricted files require explicit permission media derivatives do not expose originals without permission exports do not expose restricted files without permission external works are referenced without unauthorized copying ``` No production files are served from unmanaged public folders. --- ## 33. Content advisory verification Verify content advisory system can: ```text create tags group tags into tag sets create content markers attach locators link markers to media link markers to archive items link markers to external works review markers approve markers contest markers retire markers enforce audience suitability enforce cultural protocol restrictions ``` Verify locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Verify examples such as: ```text film content marker with timecode range book content marker with page range PDF content marker with page locator audio content marker with timestamp range external work content marker without copied media ``` --- ## 34. External work verification Verify external work records can represent: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` Verify the archive can store: ```text bibliographic metadata source ownership rights notes content markers content advisories cultural protocol notes teaching notes manual locators references ``` Verify the archive does not imply ownership over third-party works. --- ## 35. Packaging verification Before packaging, confirm the package contains: ```text root PHP files amd/src files amd/build files backup files classes files db files lang/en and lang/fr files pix/icon.svg templates tests docs ``` Before packaging, confirm the package excludes: ```text *.bak *.tmp *.orig *.rej *.patch *.log .DS_Store Thumbs.db node_modules/ runtime exports outside Moodle File API codedump files AI scratch files ``` The package root must be: ```text uckkarchive ``` The package must install to: ```text mod/uckkarchive ``` --- ## 36. Installation failure behavior If installation fails, the plugin must fail safely. Failure handling must avoid: ```text partial public file exposure partial restricted file exposure silent capability creation failure silent schema loss silent media table omission silent content advisory table omission silent external work table omission silent File API area mismatch ``` Failures should be visible through Moodle upgrade errors, PHP errors, database exceptions, or admin notifications. --- ## 37. Clean installation rule A clean installation is valid only when: ```text Moodle detects mod_uckkarchive. All required tables are created. All required capabilities are registered. All required services are registered. All required scheduled tasks are registered. All required file areas are handled. All required templates are present. All required AMD build files are present. Backup and restore are available. Privacy provider is available. Archive workflows work. Media library workflows work. Content advisory workflows work. External work references work. Restricted and culturally restricted access fail closed. ``` --- ## 38. Final installation rule ```text Install mod_uckkarchive as a Moodle activity module at mod/uckkarchive. Keep Moodle responsible for plugin lifecycle, context, roles, capabilities, files, privacy, backup, restore, services, events, settings, and rendering. Keep mod_uckkarchive responsible for its self-contained archive, media library, content advisory system, external work references, provenance, validation, revision, restriction, and export behavior. ``` This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/23_upgrade.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 4456607af4b2a464a9766d5ff36b173d108adefec586087547cd142c9c444695 CONTENT_BYTES: 31466 ================================================================================================ # 23 — Upgrade **Path:** `docs/23_upgrade.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Upgrade and migration contract for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Purpose This document defines the final upgrade contract for `mod_uckkarchive`. The upgrade process must move existing installations to the target architecture: ```text mod_uckkarchive = self-contained archive + media library + content advisory system ``` Canonical formula: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` The upgrade process must preserve archive memory, media files, provenance, revisions, restricted state, privacy behavior, backup/restore compatibility, and export identity. --- ## 2. Upgrade owner The upgrade owner is: ```text db/upgrade.php ``` The target schema owner is: ```text db/install.xml ``` Upgrade rules: ```text db/install.xml defines the full current target schema. db/upgrade.php migrates existing installs to the current target schema. ``` Upgrade must use Moodle XMLDB APIs. Upgrade must not rely on unmanaged SQL that bypasses Moodle database portability. Upgrade must be idempotent at each step through Moodle upgrade savepoints. --- ## 3. Upgrade principles Every upgrade step must follow these rules: ```text preserve existing archive records preserve existing media and file references preserve user ownership and timestamps where possible preserve provenance preserve revision history preserve validation state preserve visibility and restricted state preserve backup/restore compatibility preserve privacy provider behavior avoid public exposure of restricted data fail closed for unknown restricted or integrity-linked records ``` Upgrade must not: ```text delete archive records silently delete media files silently make restricted records public convert evidence files into unmanaged public files create gradebook records create administrative registry records create live integrity procedure records claim Assembly decision authority claim institutional reporting authority ``` --- ## 4. Version checkpoint pattern `db/upgrade.php` must use Moodle version checkpoints. Pattern: ```php if ($oldversion < 2026052701) { // Apply schema/data migration. upgrade_mod_savepoint(true, 2026052701, 'uckkarchive'); } ``` Rules: ```text Each checkpoint has one clear purpose. Each checkpoint is safe to run only once. Each checkpoint checks whether fields, tables, keys, indexes, and capabilities already exist. Each checkpoint writes an upgrade savepoint after success. ``` --- ## 5. Required target tables Required archive tables: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export ``` Required media library tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item ``` Required content advisory and external-work tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work uckkarchive_media_source ``` Table rule: ```text All target tables must exist after upgrade. All newly created tables must include stable identifiers, timestamps, user references, and indexes required by services, privacy, backup, restore, and export. ``` --- ## 6. UUID migration Stable UUIDs are mandatory. Identifier rule: ```text id = local Moodle database primary key uuid = stable portable object identity ``` UUIDs must exist for: ```text archive items proof records Kristals provenance records where exported or referenced revision records where exported or referenced export packages media objects media versions media collections media relations content markers content reviews external works media sources ``` UUID migration workflow: ```text 1. Add uuid fields where missing. 2. Backfill UUIDs for existing records. 3. Ensure UUIDs are unique. 4. Add indexes or unique keys where appropriate. 5. Preserve UUIDs in backup, restore, export, and manifests. ``` UUID rule: ```text UUIDs must be generated once and then treated as stable. Upgrade must not regenerate UUIDs for records that already have them. ``` --- ## 7. Media schema upgrade Media becomes first-class. Upgrade must ensure these tables exist: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item uckkarchive_media_source ``` Media migration workflow: ```text 1. Create media tables if missing. 2. Add source, visibility, status, audience suitability, and current version fields. 3. Backfill media objects from existing archive-owned file references where applicable. 4. Create initial media version records for existing media files where applicable. 5. Store file hash, MIME type, size, filename, and file-area metadata where available. 6. Preserve archive item links through media relations. 7. Preserve file storage in Moodle File API. 8. Mark records with conservative visibility when prior visibility is unclear. ``` Media migration rule: ```text Existing files must not be moved to unmanaged public folders. Existing files must not be duplicated unnecessarily. Existing files must remain served through Moodle File API. ``` --- ## 8. Media lifecycle backfill Canonical media states: ```text draft submitted active restricted superseded archived deleted_soft ``` Backfill rule: ```text Existing usable media should become active only when visibility and access are known. Existing restricted or uncertain media should become restricted. Existing removed media should become deleted_soft or archived according to retention policy. ``` Default mapping: | Existing condition | Target media status | |---|---| | Normal visible file with valid archive context | `active` | | File linked to restricted archive item | `restricted` | | File linked to integrity-related record | `restricted` | | File linked to culturally sensitive marker | `restricted` | | File retained for evidence/history | `archived` | | File marked removed but retained | `deleted_soft` | | Unknown status | `restricted` | Safety rule: ```text Unknown status fails closed. ``` --- ## 9. Visibility migration Canonical visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Compatibility rule: ```text institutional must normalize to institution. ``` Visibility migration workflow: ```text 1. Normalize legacy visibility values. 2. Convert institutional to institution. 3. Preserve public only when explicitly public. 4. Preserve restricted and integrity-related records as restricted_integrity where applicable. 5. Preserve cultural protocol restrictions as restricted_cultural where applicable. 6. Default unknown visibility to restricted. ``` Visibility rule: ```text Upgrade must not make private, restricted, integrity-linked, or culturally restricted data public. ``` --- ## 10. Capability upgrade Canonical archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Canonical media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Canonical content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Removed capability: ```text mod/uckkarchive:versionitem = not used ``` Capability migration rule: ```text Do not create or preserve mod/uckkarchive:versionitem as a target capability. Archive item revision uses mod/uckkarchive:reviseitem. Media versioning uses mod/uckkarchive:versionmedia. ``` Role assignment rule: ```text New powerful capabilities must not be granted broadly by upgrade unless explicitly safe. Restricted, cultural, export, advisory review, and external work management capabilities should default conservatively. ``` --- ## 11. File API upgrade Component: ```text mod_uckkarchive ``` Canonical archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Canonical content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File API upgrade workflow: ```text 1. Ensure classes/local/file_area_registry.php lists all canonical file areas. 2. Normalize legacy file area names where needed. 3. Preserve existing files in Moodle File API. 4. Attach existing files to archive or media records through stable item ids. 5. Create media version records for media files where applicable. 6. Ensure pluginfile handling recognizes canonical areas. 7. Ensure privacy, backup, restore, and tests use the registry. ``` Forbidden storage: ```text No production archive/media files in unmanaged public folders. No binary media files directly in custom database fields. No direct public file URLs as authority. ``` --- ## 12. Content advisory schema upgrade Content advisory and cultural protocol handling are first-class. Required tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review ``` Upgrade workflow: ```text 1. Create content advisory tables if missing. 2. Seed required tag sets. 3. Seed baseline advisory tags. 4. Add marker UUID support. 5. Add review state support. 6. Add audience suitability support. 7. Add cultural protocol flags. 8. Link markers to media, media versions, archive items, external works, or manual references. ``` Architecture rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 13. Content tag seed data Baseline tag sets: ```text general_advisories cultural_protocols classroom_suitability integrity_sensitive youth_access ``` Baseline content advisory tags: ```text sexual_violence violence racism colonial_violence death self_harm substance_use nudity explicit_language culturally_sensitive sacred_content ceremonial_content restricted_knowledge grief_or_mourning requires_context not_for_children ``` Baseline cultural protocol tags: ```text community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export ``` Seed rule: ```text Seed records must be inserted only if missing. Existing edited records must not be overwritten by upgrade. ``` --- ## 14. Content marker upgrade Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Content marker migration workflow: ```text 1. Create marker table if missing. 2. Add locator fields. 3. Add target fields for media, media version, archive item, external work, or manual reference. 4. Add advisory tag linkage. 5. Add review state. 6. Add visibility and audience suitability fields. 7. Default uncertain sensitive markers to pending_review or restricted. ``` Marker rule: ```text Content markers must not expose sensitive locator details to unauthorized users. ``` --- ## 15. Content review upgrade Canonical review states: ```text draft pending_review reviewed approved contested retired ``` Content review migration workflow: ```text 1. Create review table if missing. 2. Add reviewer user reference. 3. Add review state. 4. Add rationale/note fields. 5. Add timestamps. 6. Add files through content_review_files where needed. 7. Ensure review records are included in privacy, backup, restore, and export manifests. ``` AI rule: ```text AI may suggest tags or markers. AI cannot approve content advisories. AI cannot approve cultural protocol access. Human review is required before advisory status becomes approved. ``` --- ## 16. External work upgrade External works are represented by: ```text uckkarchive_external_work ``` External work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` Upgrade workflow: ```text 1. Create external work table if missing. 2. Add UUID, title, creator, year, source, URL, identifier, rights note, and citation fields. 3. Add visibility and audience suitability fields. 4. Add provenance and user references. 5. Link external works to content markers, media relations, archive items, or collections. ``` External work rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` --- ## 17. Media source upgrade Media source records are represented by: ```text uckkarchive_media_source ``` Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` Upgrade workflow: ```text 1. Create media source table if missing. 2. Add source type and ownership fields. 3. Backfill source records for existing media where possible. 4. Default unknown source to unknown_source. 5. Default rights uncertainty to restricted_reference where appropriate. 6. Link media records to media source records. ``` Source rule: ```text Unknown source must not be treated as public domain. ``` --- ## 18. Provenance upgrade Canonical provenance values: ```text human ai_assisted imported system archive assembly challenge integrity media external_work content_review ``` Provenance migration workflow: ```text 1. Ensure provenance table supports source component, source area, source id, UUID, actor, timestamp, and metadata. 2. Normalize provenance values. 3. Add missing provenance records where safe. 4. Preserve source references for imported or external records. 5. Add provenance links for media versions, external works, content markers, and reviews. ``` Provenance rule: ```text Provenance explains origin. Provenance does not grant authority by itself. ``` --- ## 19. Validation upgrade Canonical validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Validation migration workflow: ```text 1. Normalize validation state values. 2. Preserve contested and invalidated states. 3. Default unknown validation state to unverified. 4. Do not auto-verify archive records. 5. Do not auto-approve advisory review records. 6. Do not auto-approve cultural protocol access. ``` Validation rules: ```text Validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. ``` --- ## 20. Archive item status upgrade Canonical archive item statuses: ```text draft submitted under_review validated published restricted contested invalidated superseded archived ``` Status migration workflow: ```text 1. Normalize old status values. 2. Preserve restricted, contested, invalidated, and archived states. 3. Map active published records only when access policy confirms visibility. 4. Default uncertain records to restricted or under_review. ``` Status rule: ```text Unknown or sensitive state fails closed. ``` --- ## 21. Media relation upgrade Canonical media relation types: ```text belongs_to_item belongs_to_kristal belongs_to_collection is_derivative_of is_translation_of is_excerpt_of is_proof_for is_source_for replaces references duplicates references_external_work contains_content_marker ``` Relation upgrade workflow: ```text 1. Create relation table if missing. 2. Backfill item-file links as belongs_to_item. 3. Backfill Kristal links as belongs_to_kristal. 4. Backfill collection links as belongs_to_collection. 5. Backfill derivative/thumbnail/source references where known. 6. Link external works through references_external_work. 7. Link markers through contains_content_marker where needed. ``` Relation rule: ```text Relations describe graph meaning. Relations do not transfer ownership to external plugins or external rights holders. ``` --- ## 22. Collection upgrade Collections are represented by: ```text uckkarchive_media_collection uckkarchive_media_collection_item ``` Collection upgrade workflow: ```text 1. Create collection tables if missing. 2. Generate UUIDs for existing logical bundles where applicable. 3. Preserve ordering. 4. Preserve visibility. 5. Preserve restricted state. 6. Link collection items by media id and UUID. ``` Collection examples: ```text course pack Kristal source pack challenge evidence pack assembly record pack public media set restricted proof bundle external work study set cultural protocol set ``` Collection rule: ```text Collections group media. Collections do not duplicate media files. Collections do not override media-level restrictions. ``` --- ## 23. Export upgrade Export records are represented by: ```text uckkarchive_export ``` Canonical export file areas: ```text export_package export_manifest ``` Canonical manifest filename: ```text manifest.json ``` Export upgrade workflow: ```text 1. Ensure export table exists. 2. Add UUID, status, actor, reason, timestamp, redaction, visibility, and manifest metadata fields. 3. Preserve existing export package files. 4. Generate manifest records for future exports. 5. Do not retroactively expose restricted content through regenerated manifests. ``` Manifest includes: ```text plugin component archive id export id export timestamp export actor export reason archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Export rule: ```text Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` --- ## 24. Service upgrade External service declarations belong in: ```text db/services.php ``` Upgrade must ensure services exist for: ```text archive workflows media workflows media collections media versions media relations media tags content tags content tag sets content markers content reviews external works export preview export generation export status ``` Service rule: ```text Services must check context, capability, visibility, status, content advisory rules, cultural protocol restrictions, redaction, and retention. ``` No service may expose restricted records through incomplete filtering. --- ## 25. Event upgrade Observer registration belongs in: ```text db/events.php ``` Event classes include: ```text classes/event/archive_viewed.php classes/event/archive_item_created.php classes/event/archive_item_validated.php classes/event/archive_item_revised.php classes/event/archive_item_exported.php classes/event/media_created.php classes/event/media_updated.php classes/event/media_version_created.php classes/event/media_collection_created.php classes/event/media_exported.php classes/event/content_marker_created.php classes/event/content_marker_reviewed.php classes/event/external_work_created.php ``` Event rule: ```text Events audit successful state changes. Events must not expose restricted content, raw content, private cultural protocol notes, or redacted details. ``` --- ## 26. Scheduled task upgrade Task declarations belong in: ```text db/tasks.php ``` Required task files: ```text classes/task/generate_archive_exports.php classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/purge_expired_exports.php classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php classes/task/validate_pending_items.php ``` Task upgrade workflow: ```text 1. Add db/tasks.php if missing. 2. Register scheduled tasks. 3. Ensure tasks reuse classes/local policy. 4. Ensure derivative and thumbnail tasks respect restricted and cultural states. 5. Ensure export purge respects retention. ``` Task rule: ```text Scheduled tasks do not bypass policy checks for generated outputs. ``` --- ## 27. Privacy provider upgrade Privacy provider: ```text classes/privacy/provider.php ``` Privacy provider must cover: ```text archive items media records media versions media files media collections media relations media tags content tags when user-created content tag sets when user-created content markers content reviews external works when user-created or user-linked media sources proofs Kristals provenance revisions exports ``` Privacy upgrade workflow: ```text 1. Add privacy coverage for new tables. 2. Add user data export logic. 3. Add deletion/anonymization/preservation logic. 4. Add redaction rules for restricted, cultural, integrity, third-party, and advisory data. 5. Add tests for new privacy surfaces. ``` Privacy rule: ```text Privacy export is not a permission bypass. Restricted third-party information and culturally restricted details must be filtered or redacted. ``` --- ## 28. Backup and restore upgrade Backup and restore files: ```text backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` Backup/restore must include: ```text archive records media records media versions media files media relations media tags media collections media collection membership media source records external work records content tags content tag sets content markers content reviews provenance revisions export manifests restricted visibility audience suitability cultural protocol flags ``` Restore rule: ```text Restore must not make restricted, culturally sensitive, or integrity-linked records public. ``` --- ## 29. Language string upgrade Language files: ```text lang/en/uckkarchive.php lang/fr/uckkarchive.php ``` Language strings must exist for: ```text new capabilities media library UI media versions media collections media relations media source external works content advisories content tags content tag sets content markers content reviews audience suitability cultural protocol restricted integrity restricted cultural privacy provider backup/restore service errors events scheduled tasks ``` Language rule: ```text Language files must not contain active strings for removed target capability mod/uckkarchive:versionitem. English and French public UI strings must remain aligned. ``` --- ## 30. Settings upgrade Settings file: ```text settings.php ``` Settings may include: ```text enablemedialibrary enablecontentadvisories enableexternalworks enableintegrityintegration allowmediaexports allowcollectionexports defaultmediavisibility defaultaudiencesuitability defaultrestrictedhandling defaultredaction showadvisorybadges ``` Default values should be conservative: ```text defaultmediavisibility = course or restricted according to site policy defaultaudiencesuitability = guided when unknown defaultrestrictedhandling = fail_closed defaultredaction = enabled enableintegrityintegration = disabled unless explicitly enabled ``` Settings rule: ```text Settings cannot bypass context, capability, privacy, redaction, cultural protocol, content advisory, or retention policy. ``` --- ## 31. Cache and search upgrade Search/index maintenance task: ```text classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php ``` Upgrade workflow: ```text 1. Mark media search index stale after schema changes. 2. Mark content marker index stale after advisory schema changes. 3. Queue rebuild tasks. 4. Rebuild only permission-filtered indexes. 5. Ensure restricted records are not leaked through facets, counts, snippets, previews, or thumbnails. ``` Search rule: ```text Search results are permission-filtered. Restricted records are not leaked through metadata. ``` --- ## 32. Integrity integration upgrade `tool_uckkintegrity` is optional. Upgrade must preserve: ```text ordinary archive operation without tool_uckkintegrity ordinary media operation without tool_uckkintegrity ordinary content advisory operation without tool_uckkintegrity ``` Integrity upgrade workflow: ```text 1. Add restricted_integrity visibility support. 2. Add integrity source provenance support. 3. Add integrity export file area support. 4. Add optional settings for integrity integration. 5. Ensure integrity-specific features fail closed when tool_uckkintegrity is absent. ``` Integrity rule: ```text mod_uckkarchive may preserve integrity-related records. mod_uckkarchive must not own integrity procedure authority. ``` --- ## 33. Report integration upgrade `report_uckk` owns institutional reporting. Upgrade must preserve this boundary: ```text mod_uckkarchive = archive-owned export packages report_uckk = institutional reporting views and institutional report exports ``` Reporting rule: ```text Upgrade must not convert archive export records into institutional report authority. ``` --- ## 34. Assembly integration upgrade `mod_uckkassembly` owns Assembly decision authority. Upgrade may preserve: ```text assembly snapshots decision attachments minutes files proof bundles archive summaries media relations ``` Upgrade must not create: ```text live Assembly decision records Assembly voting authority Assembly procedure state ``` Assembly rule: ```text Preserved Assembly-related records are archive memory, not active Assembly authority. ``` --- ## 35. Challenge integration upgrade `mod_uckkchallenge` owns challenge workflow state. Upgrade may preserve: ```text challenge evidence challenge media challenge proof records challenge summary snapshots Kristal source packs ``` Upgrade must not create: ```text live challenge workflow state challenge grading authority challenge decision authority ``` Challenge rule: ```text Preserved challenge-related records are archive/media memory, not active challenge workflow authority. ``` --- ## 36. Rollback and failure behavior Moodle upgrade steps are not general-purpose rollback scripts. Failure behavior: ```text each step must be atomic where possible each step must check existence before creating schema objects each step must avoid destructive data changes each step must leave restricted data protected if interrupted each step must write savepoint only after success ``` Failure rule: ```text If migration cannot determine safe visibility or authority, records must remain restricted. ``` --- ## 37. Data integrity checks After upgrade, checks must verify: ```text all target tables exist all required UUID fields exist UUIDs are populated UUIDs are unique where required canonical file areas are recognized capabilities are defined removed capability is not target-defined services are declared tasks are declared privacy provider covers new tables backup/restore includes new tables restricted records remain restricted content advisory seed data exists external work references are preserved media source records exist where needed ``` Data integrity rule: ```text Upgrade success means target behavior is reachable and protected, not merely that schema changes ran. ``` --- ## 38. Test requirements Upgrade tests must cover: ```text fresh install target schema upgrade from archive-only data upgrade with existing files upgrade with restricted records upgrade with integrity-linked records upgrade with external works upgrade with content advisories upgrade with collections and relations upgrade with missing optional tool_uckkintegrity upgrade does not create mod/uckkarchive:versionitem upgrade does not make restricted data public upgrade preserves Moodle File API files upgrade preserves backup/restore behavior upgrade preserves privacy provider behavior ``` Recommended test files: ```text tests/upgrade_test.php tests/media_library_test.php tests/content_advisory_test.php tests/external_work_test.php tests/backup_restore_test.php tests/privacy_provider_test.php tests/services_test.php ``` Testing rule: ```text Tests verify the final target behavior, not historical transitions. ``` --- ## 39. Developer implementation checklist Implementation must update: ```text db/install.xml db/upgrade.php db/access.php db/services.php db/events.php db/tasks.php lib.php settings.php classes/privacy/provider.php backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php lang/en/uckkarchive.php lang/fr/uckkarchive.php tests/upgrade_test.php ``` Implementation must add or confirm: ```text classes/local/file_area_registry.php classes/local/uuid.php classes/local/media.php classes/local/media_version.php classes/local/media_collection.php classes/local/media_relation.php classes/local/media_source.php classes/local/content_tag.php classes/local/content_tag_set.php classes/local/content_marker.php classes/local/content_review.php classes/local/content_policy.php classes/local/external_work.php ``` Implementation rule: ```text Upgrade code, install schema, services, privacy, backup/restore, and tests must describe the same target model. ``` --- ## 40. Final upgrade rule ```text The upgrade process converts mod_uckkarchive into the final self-contained archive, media library, and content advisory module. It preserves archive memory, media files, source records, external works, content advisories, cultural protocol markers, provenance, revisions, exports, privacy behavior, backup/restore behavior, and restricted states. It must not make restricted data public. It must not create external domain authority. It must not preserve removed capabilities as target behavior. It must fail closed when safety, visibility, source, or authority is uncertain. This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ``` ================================================================================================ FILE: mod/uckkarchive/docs/24_release_spec.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: b84c4e1c9480be88a982b72983e596f70da3cdf121661c4b67e54f5ef91e3f00 CONTENT_BYTES: 28753 ================================================================================================ # 24 — Release Specification **Path:** `docs/24_release_spec.md` **Plugin:** `mod_uckkarchive` **Component:** `mod_uckkarchive` **Status:** Final target specification **Scope:** Release package, build requirements, file inclusion/exclusion, installation readiness, upgrade readiness, tests, privacy, backup/restore, UI assets, and packaging rules for the self-contained UCKK Archive, Media Library, and Content Advisory Moodle activity module. --- ## 1. Purpose This document defines the final release specification for `mod_uckkarchive`. It is not a release history. It is not a changelog. It is not a gap register. It is not an acceptance checklist. It defines what the clean release package must contain and how it must be prepared for installation, duplication, troubleshooting, and deployment. Canonical module formula: ```text mod_uckkarchive = archive engine + media library engine + content advisory system + Moodle adapter layer ``` Canonical architecture rule: ```text Moodle-native on the outside. Self-contained archive/media/content-advisory system on the inside. ``` --- ## 2. Release package root The release package root is: ```text mod/uckkarchive ``` Source path: ```text C:\mycode\UCKK\uckk-moodle\mod\uckkarchive ``` Active Moodle path: ```text C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive ``` The release package must install as the Moodle component: ```text mod_uckkarchive ``` The release package must not depend on being installed outside Moodle’s normal plugin structure. --- ## 3. Release identity Required plugin identity: ```text PLUGIN_NAME = UCKK Archive PLUGIN_TYPE = mod PLUGIN_FOLDER = uckkarchive MOODLE_COMPONENT = mod_uckkarchive MOODLE_PLUGIN_PATH = mod/uckkarchive ``` Required Moodle metadata file: ```text version.php ``` `version.php` must define: ```text $plugin->component = 'mod_uckkarchive'; $plugin->version $plugin->requires $plugin->maturity $plugin->release ``` Dependency rule: ```text mod_uckkarchive must not declare a dependency on itself. ``` Integrity dependency rule: ```text tool_uckkintegrity is an optional integration. Ordinary archive/media/content-advisory operation must not require tool_uckkintegrity. ``` --- ## 4. Required top-level files The release package must include: ```text add.php export.php index.php item.php lib.php locallib.php media.php mod_form.php settings.php styles.css validate.php version.php view.php ``` Top-level file rule: ```text Root PHP files coordinate requests only. Business policy belongs in classes/local. Service contracts belong in classes/external. Renderable payloads belong in classes/output. ``` --- ## 5. Required top-level folders The release package must include: ```text amd/ backup/ classes/ db/ docs/ lang/ pix/ templates/ tests/ ``` The following folders must not be used to store production user media: ```text pix/ docs/ templates/ amd/ ``` Production archive and media files must be stored through Moodle File API only. --- ## 6. Required documentation files The clean documentation set must include: ```text docs/_alignment_variables.md docs/00_index.md docs/01_architecture_decision.md docs/02_domain_boundaries.md docs/03_file_architecture.md docs/04_data_model.md docs/05_media_library.md docs/06_file_api_and_storage.md docs/07_permissions_and_roles.md docs/08_archive_workflows.md docs/09_media_workflows.md docs/10_provenance_versioning_validation.md docs/11_privacy_retention_redaction.md docs/12_backup_restore.md docs/13_services_and_ajax_api.md docs/14_events_and_audit.md docs/15_ui_templates_and_amd.md docs/16_integration_with_courses.md docs/17_integration_with_challenges.md docs/18_integration_with_assemblies.md docs/19_integration_with_integrity.md docs/20_reporting_and_exports.md docs/21_testing_strategy.md docs/22_installation.md docs/23_upgrade.md docs/24_release_spec.md ``` Documentation rule: ```text Documentation describes the final target state. Documentation does not keep historical gap records. Documentation does not contain release notes. Documentation does not contain acceptance-checklist process documents. ``` --- ## 7. Files excluded from the clean documentation set The clean documentation set must not include: ```text docs/05_media_database_division.md docs/09_didactic_material_workflows.md docs/24_acceptance_checklist.md docs/25_known_gaps_and_corrections.md docs/26_release_notes.md docs/27_file_architecture_manifest.md ``` Replacement mapping: | Removed file | Replacement | |---|---| | `docs/05_media_database_division.md` | `docs/05_media_library.md` | | `docs/09_didactic_material_workflows.md` | `docs/08_archive_workflows.md` and `docs/09_media_workflows.md` | | `docs/24_acceptance_checklist.md` | `docs/24_release_spec.md` | | `docs/25_known_gaps_and_corrections.md` | No replacement. Historical gap registry is not part of final-state docs. | | `docs/26_release_notes.md` | No replacement. Release notes are not part of this final-state specification set. | | `docs/27_file_architecture_manifest.md` | `docs/03_file_architecture.md` | --- ## 8. Required database files The release package must include: ```text db/access.php db/events.php db/install.xml db/services.php db/tasks.php db/upgrade.php ``` Database release rule: ```text db/install.xml defines the full current target schema. db/upgrade.php migrates existing installs to the full current target schema. ``` The release must include database support for: ```text archive records media records media versions media collections media collection membership media relations media tags media source records content advisory tags content tag sets content markers content reviews external works proofs Kristals provenance revisions exports ``` --- ## 9. Required database tables Required archive tables: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_kristal uckkarchive_prov uckkarchive_rev uckkarchive_export ``` Required media library tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_collection uckkarchive_media_collection_item uckkarchive_media_source ``` Required content advisory and external-work tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work ``` Identifier rule: ```text id = local Moodle database primary key uuid = stable portable object identity ``` Release schema rule: ```text Archive objects, media objects, content markers, external works, and export packages must support UUID identity for export, restore, duplication, and cross-site portability. ``` --- ## 10. Required capabilities Archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Removed capability: ```text mod/uckkarchive:versionitem ``` The release must not use or document `mod/uckkarchive:versionitem`. Archive item revision uses: ```text mod/uckkarchive:reviseitem ``` Media versioning uses: ```text mod/uckkarchive:versionmedia ``` --- ## 11. Required local domain classes The release package must include: ```text classes/local/archive_item.php classes/local/archive_policy.php classes/local/content_marker.php classes/local/content_policy.php classes/local/content_review.php classes/local/content_tag.php classes/local/content_tag_set.php classes/local/context_resolver.php classes/local/export_package.php classes/local/external_work.php classes/local/file_area_registry.php classes/local/kristal.php classes/local/manifest_builder.php classes/local/media.php classes/local/media_collection.php classes/local/media_file.php classes/local/media_policy.php classes/local/media_relation.php classes/local/media_search.php classes/local/media_source.php classes/local/media_tag.php classes/local/media_version.php classes/local/metadata_validator.php classes/local/proof.php classes/local/provenance.php classes/local/revision.php classes/local/uuid.php ``` Local class rule: ```text classes/local is the authority layer for archive, media, content advisory, and export behavior. ``` --- ## 12. Required external service classes The release package must include archive services: ```text classes/external/add_item.php classes/external/add_proof.php classes/external/create_kristal.php classes/external/export_items.php classes/external/get_archive.php classes/external/get_archive_item.php classes/external/get_archive_item_card.php classes/external/get_archive_items.php classes/external/get_export_preview.php classes/external/get_export_status.php classes/external/get_kristal.php classes/external/get_proofs.php classes/external/get_provenance_panel.php classes/external/get_restricted_item.php classes/external/get_revisions.php classes/external/revise_item.php classes/external/save_item_draft.php classes/external/update_kristal.php classes/external/update_provenance.php classes/external/validate_item.php ``` The release package must include media services: ```text classes/external/add_media.php classes/external/add_media_relation.php classes/external/add_media_to_collection.php classes/external/add_media_version.php classes/external/add_media_collection.php classes/external/delete_media.php classes/external/export_collection.php classes/external/export_media.php classes/external/get_media.php classes/external/get_media_card.php classes/external/get_media_collection.php classes/external/get_media_collections.php classes/external/get_media_item.php classes/external/get_media_relations.php classes/external/get_media_versions.php classes/external/remove_media_from_collection.php classes/external/remove_media_relation.php classes/external/search_media.php classes/external/tag_media.php classes/external/untag_media.php classes/external/update_media.php classes/external/update_media_collection.php ``` The release package must include content advisory and external work services: ```text classes/external/add_content_marker.php classes/external/add_external_work.php classes/external/delete_content_marker.php classes/external/get_content_markers.php classes/external/get_content_tag_sets.php classes/external/get_content_tags.php classes/external/get_external_work.php classes/external/get_external_works.php classes/external/review_content_marker.php classes/external/update_content_marker.php classes/external/update_external_work.php ``` Service rule: ```text Every service checks context, capability, policy, visibility, lifecycle state, content advisory policy, cultural protocol restrictions, retention, and redaction server-side. ``` --- ## 13. Required form classes The release package must include: ```text classes/form/archive_item_form.php classes/form/content_marker_form.php classes/form/content_review_form.php classes/form/content_tag_form.php classes/form/export_form.php classes/form/external_work_form.php classes/form/kristal_form.php classes/form/media_collection_form.php classes/form/media_form.php classes/form/media_relation_form.php classes/form/media_version_form.php classes/form/validation_form.php ``` Form rule: ```text Forms collect and shape input. Final authority remains in classes/local policy and domain classes. ``` --- ## 14. Required output classes The release package must include: ```text classes/output/archive_item_card.php classes/output/archive_view.php classes/output/content_advisory_panel.php classes/output/external_work_card.php classes/output/kristal_card.php classes/output/media_card.php classes/output/media_collection.php classes/output/media_library.php classes/output/media_version_list.php classes/output/provenance_panel.php classes/output/renderer.php ``` Recommended output classes: ```text classes/output/export_preview.php classes/output/media_relation_list.php classes/output/restricted_notice.php classes/output/validation_panel.php ``` Output rule: ```text Output classes format permission-filtered data. Output classes must not authorize access or expose hidden metadata. ``` --- ## 15. Required templates The release package must include: ```text templates/archive_item_card.mustache templates/archive_view.mustache templates/content_advisory_panel.mustache templates/external_work_card.mustache templates/kristal_card.mustache templates/media_card.mustache templates/media_collection.mustache templates/media_library.mustache templates/media_relation_list.mustache templates/media_upload.mustache templates/media_version_list.mustache templates/proof_card.mustache templates/provenance_panel.mustache templates/validation_panel.mustache ``` Recommended templates: ```text templates/action_menu.mustache templates/empty_state.mustache templates/export_preview.mustache templates/filter_bar.mustache templates/restricted_notice.mustache ``` Template rule: ```text Templates render pre-filtered data. Templates must not contain hidden restricted data for later client-side display. ``` --- ## 16. Required AMD files Required AMD source files: ```text amd/src/archive.js amd/src/content_advisory.js amd/src/export.js amd/src/external_work.js amd/src/kristal.js amd/src/media.js amd/src/media_collection.js ``` Required AMD build files: ```text amd/build/archive.min.js amd/build/content_advisory.min.js amd/build/export.min.js amd/build/external_work.min.js amd/build/kristal.min.js amd/build/media.min.js amd/build/media_collection.min.js ``` AMD rule: ```text amd/src is source. amd/build is generated. Generated AMD build files are not edited by hand. ``` Release build rule: ```text A release package must include generated amd/build files. ``` --- ## 17. Required event classes The release package must include: ```text classes/event/archive_viewed.php classes/event/archive_item_created.php classes/event/archive_item_validated.php classes/event/archive_item_revised.php classes/event/archive_item_exported.php classes/event/content_marker_created.php classes/event/content_marker_reviewed.php classes/event/external_work_created.php classes/event/media_collection_created.php classes/event/media_created.php classes/event/media_exported.php classes/event/media_updated.php classes/event/media_version_created.php ``` Event rule: ```text Events audit successful state changes. Events must not expose raw media, restricted content, private cultural protocol notes, hidden integrity details, or redacted data. ``` --- ## 18. Required scheduled tasks The release package must include: ```text classes/task/generate_archive_exports.php classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/purge_expired_exports.php classes/task/rebuild_content_marker_index.php classes/task/rebuild_media_search.php classes/task/validate_pending_items.php ``` Scheduled task registration belongs in: ```text db/tasks.php ``` Task rule: ```text Scheduled tasks reuse classes/local domain logic. Scheduled tasks do not bypass policy checks for generated outputs. ``` --- ## 19. Required backup and restore files The release package must include: ```text backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` Backup/restore must preserve: ```text archive records archive items proofs Kristals provenance revisions exports media records media versions media collections media collection membership media relations media tags media source records content tags content tag sets content markers content reviews external works file areas UUIDs visibility restricted state audience suitability cultural protocol flags manifest references ``` Backup/restore rule: ```text Restore reconstructs module-owned state. Restore does not create external authority or make restricted material public. ``` --- ## 20. Required privacy provider The release package must include: ```text classes/privacy/provider.php ``` The privacy provider must cover: ```text archive records created by user archive records modified by user proof records created by user Kristals created by user provenance records involving user revision records created by user export records created by user media records created by user media versions created by user media collections created by user media relations created by user media tags created by user media source records created by user content markers created by user content reviews performed by user external works created by user files uploaded by user review notes containing personal data metadata containing personal data ``` Privacy rule: ```text Privacy export is not a permission bypass. Restricted cultural protocol notes and third-party data must be redacted or filtered. ``` --- ## 21. Required language files The release package must include: ```text lang/en/uckkarchive.php lang/fr/uckkarchive.php ``` Language files must include strings for: ```text plugin identity capabilities settings forms services events archive UI media UI collections relations versions content advisories cultural protocols external works validation privacy backup/restore exports errors warnings access messages ``` Language rule: ```text Every public UI string has matching English and French keys. Templates and AMD modules use language strings, not hard-coded display text. ``` --- ## 22. Required pix files The release package must include: ```text pix/icon.svg ``` Recommended pix files: ```text pix/media.svg pix/collection.svg pix/content_advisory.svg pix/external_work.svg ``` Pix rule: ```text pix contains static plugin interface assets only. User-uploaded media never belongs in pix. ``` --- ## 23. Required tests The release package must include: ```text tests/archive_test.php tests/backup_restore_test.php tests/content_advisory_test.php tests/export_test.php tests/external_work_test.php tests/file_api_test.php tests/lib_test.php tests/media_library_test.php tests/privacy_provider_test.php tests/services_test.php tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` Testing coverage must include: ```text installation schema upgrade migration capabilities archive workflows media workflows media versioning media collections media relations media tags media source records external works content advisory tags content tag sets content markers content reviews file areas pluginfile access privacy provider backup/restore export manifest restricted access cultural protocol restrictions service authorization UI rendering AMD service error handling ``` Testing rule: ```text Tests verify final target behavior, not historical transitions. ``` --- ## 24. Required File API areas Canonical archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Canonical content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File-area rule: ```text classes/local/file_area_registry.php is the central file-area registry. Pluginfile handling, privacy, backup, restore, services, and tests must use the registry. ``` --- ## 25. Export package requirements Archive/media export packages must include: ```text manifest.json ``` The manifest must include: ```text plugin component archive id export id export timestamp export actor export reason archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Export rule: ```text Exports are portable and explainable. Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` --- ## 26. Build requirements Before packaging, generated files must be current. Required generated AMD build outputs: ```text amd/build/archive.min.js amd/build/content_advisory.min.js amd/build/export.min.js amd/build/external_work.min.js amd/build/kristal.min.js amd/build/media.min.js amd/build/media_collection.min.js ``` Build rule: ```text Do not ship stale AMD build files. Do not edit generated AMD build files manually. ``` The release package must not require a developer build step to run after installation in ordinary Moodle use. --- ## 27. Installation requirements The release package must install cleanly from: ```text mod/uckkarchive ``` Installation must create: ```text all required archive tables all required media tables all required content advisory tables all required external work tables all capabilities all scheduled tasks all service declarations all event observers ``` Installation must not require: ```text manual database edits manual file area creation manual public folder creation manual copying of user media hard dependency on tool_uckkintegrity ``` --- ## 28. Upgrade requirements Upgrade must support existing installs through: ```text db/upgrade.php ``` Upgrade must be able to add or migrate: ```text media tables media source records media versions media collections media relations content tags content tag sets content markers content reviews external works new file areas new capabilities new service declarations new scheduled tasks UUID fields visibility normalization ``` Upgrade rule: ```text Upgrade must preserve existing archive data. Upgrade must not make restricted records public. Upgrade must not delete user files unless explicitly governed by retention policy. ``` Compatibility normalization: ```text institutional -> institution ``` --- ## 29. Security requirements The release must enforce: ```text require_login context validation capability checks sesskey checks for mutations server-side policy checks Moodle File API pluginfile checks service parameter validation service return filtering privacy-aware redaction restricted data filtering cultural protocol filtering ``` Security rule: ```text No template, AMD module, or client-side filter is trusted as an authority layer. ``` --- ## 30. Privacy requirements The release must support: ```text privacy metadata declaration user data export user data deletion where permitted context deletion where permitted redaction where required retention-aware deletion restricted data filtering third-party data filtering cultural protocol note protection ``` Privacy rule: ```text Privacy compliance must include archive, media, content advisory, external work, and file records owned by the module. ``` --- ## 31. Backup/restore requirements The release must support Moodle backup and restore for: ```text activity instance archive records media records content advisory records external works files UUID mappings relations collections visibility review states restricted states export manifests ``` Restore rule: ```text Restored data remains subject to restored capabilities, visibility, restricted state, content advisory rules, and cultural protocol rules. ``` --- ## 32. UI release requirements The release UI must include: ```text archive view archive item card media library media card media upload media collection media version list media relation list content advisory panel content marker locator display content review UI external work card proof card Kristal card provenance panel validation panel export preview restricted notice ``` UI rule: ```text The UI must render only policy-filtered data. The UI must not leak restricted archive, media, cultural protocol, content review, or external work metadata. ``` --- ## 33. Content advisory release requirements The release must support: ```text content advisory tags content tag sets content markers content reviews cultural protocol tags audience suitability locator types external work markers internal media markers manual reference markers review states restricted cultural visibility ``` Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Content advisory rule: ```text A content advisory does not ban media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` --- ## 34. External work release requirements The release must support external works such as: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` External work rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` --- ## 35. Non-release files The release package must not include: ```text *.bak *.tmp *.orig *.rej *.patch *.log .DS_Store Thumbs.db node_modules/ vendor/ unless intentionally required and documented runtime export files outside Moodle File API codedump files AI scratch files local environment notes database dumps test output artifacts coverage reports ``` Known non-release example pattern: ```text lang/en/uckkarchive.php.bak_* ``` Backup language files must not be shipped. --- ## 36. Packaging layout The final package must expand to: ```text uckkarchive/ ├── add.php ├── export.php ├── index.php ├── item.php ├── lib.php ├── locallib.php ├── media.php ├── mod_form.php ├── settings.php ├── styles.css ├── validate.php ├── version.php ├── view.php ├── amd/ ├── backup/ ├── classes/ ├── db/ ├── docs/ ├── lang/ ├── pix/ ├── templates/ └── tests/ ``` Packaging rule: ```text The ZIP root should be uckkarchive/, not mod/uckkarchive/uckkarchive/ and not a repository wrapper folder. ``` --- ## 37. Duplication and reuse requirements The module must be structured so troubleshooting can focus on: ```text mod_uckkarchive code mod_uckkarchive tables mod_uckkarchive capabilities mod_uckkarchive file areas mod_uckkarchive services mod_uckkarchive privacy provider mod_uckkarchive backup/restore logic mod_uckkarchive UI ``` Duplication rule: ```text The module must remain modular enough to duplicate or adapt for future archive/media use cases without becoming detached from Moodle APIs. ``` --- ## 38. Release verification commands Before release, the implementation should be compatible with Moodle checks for: ```text PHP syntax Moodle code checker PHPUnit tests Behat tests AMD build generation install test upgrade test backup/restore test privacy provider test external services test ``` Command names and exact tooling may vary by Moodle development environment. The release specification requires the corresponding checks, not a particular local shell layout. --- ## 39. Final release rule A clean `mod_uckkarchive` release contains a Moodle-native, self-contained archive/media/content-advisory module. It includes the database schema, upgrade path, capabilities, services, tasks, events, File API areas, privacy provider, backup/restore implementation, UI layer, AMD build files, templates, tests, and final-state documentation needed to install, troubleshoot, duplicate, and maintain the module. This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ================================================================================================ FILE: mod/uckkarchive/docs/26_operations_app_runtime_contract.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 80c6b5a910c1065a2714c823bf6d5ff0c377d92d836a7609933c0b586baba461 CONTENT_BYTES: 16882 ================================================================================================ # 26 — Operations App Runtime Contract **Path recommandé:** `docs/26_operations_app_runtime_contract.md` **Statut:** Final target specification **Portée:** Application / GUI d’opérations UCKK pour synchronisation, seed, serveur, caches et vérifications runtime. **Source opérationnelle:** Notes d’intervention du 2026-06-01. **But:** Définir un contrat stable pour éviter les erreurs de déploiement, les confusions entre fichiers source et état Moodle réel, les blocages SSH invisibles, les seeds appliqués en mauvais mode et les chemins serveur incorrects. --- ## 1. Décision canonique L’app d’opérations UCKK n’est pas seulement une interface de boutons. Elle est une console guidée qui connaît : ```text Repo source Runtime Moodle DB Moodle SSH readiness Seed mode Cache state Smoke-test state ``` Formule canonique : ```text L’app ne suppose pas qu’un fichier source est déjà actif dans Moodle. L’app vérifie les préconditions avant chaque action serveur. L’app rend visibles les modes, chemins, commandes, résultats et jonctions critiques. ``` Règle finale : ```text Aucune action serveur ne doit être lancée si SSH n’est pas prêt. Aucune application de seed ne doit laisser Moodle en mode apply. Aucune purge cache ne doit supposer un seul chemin fixe. ``` --- ## 2. Modèle mental obligatoire Toujours distinguer : ```text Repo source Runtime Moodle DB Moodle ``` Définition : | Couche | Description | Exemple | |---|---|---| | `Repo source` | Fichiers officiels versionnés Git | `academic_registry_json/categories.json` | | `Runtime Moodle` | Moodle réellement exécuté sur le serveur | `/var/www/moodle/public` | | `DB Moodle` | Données réellement affichées par Moodle | catégories visibles dans `/course/index.php` | Règle : ```text Modifier un fichier source ne modifie pas automatiquement ce que Moodle affiche. ``` Exemple canonique : ```text categories.json = recette seed categories = appliquer la recette DB Moodle = ce que Moodle affiche ``` --- ## 3. Variables canoniques — chemins | Variable | Valeur canonique | Rôle | |---|---|---| | `LOCAL_SOURCE_REPO_ROOT` | `C:\mycode\UCKK\uckk-moodle` | Repo source local. | | `SERVER_SOURCE_REPO_ROOT` | `/opt/uckk/uckk-moodle` | Repo source serveur. | | `MOODLE_PUBLIC_ROOT` | `/var/www/moodle/public` | Racine Moodle publique observée. | | `MOODLE_REAL_ROOT` | `/var/www/moodle` | Racine Moodle réelle observée. | | `MOODLE_CONFIG_PATH` | `/var/www/moodle/config.php` | Fichier config Moodle. | | `ACADEMIC_REGISTRY_PATH` | `academic_registry_json` | Registre source JSON. | | `UCKKSEED_CLI_PUBLIC_PATH` | `/var/www/moodle/public/admin/tool/uckkseed/cli/seed.php` | CLI seed observé. | | `CACHE_PURGE_PRIMARY_PATH` | `/var/www/moodle/public/admin/cli/purge_caches.php` | Chemin purge attendu. | | `CACHE_PURGE_FALLBACK_PATH` | `/var/www/moodle/admin/cli/purge_caches.php` | Chemin purge réel trouvé. | Règle : ```text Les chemins peuvent différer entre documentation et serveur. L’app doit détecter les chemins critiques au lieu de les supposer. ``` --- ## 4. Variables canoniques — SSH | Variable | Valeur canonique | |---|---| | `SSH_USER` | `ubuntu` | | `SSH_HOST` | `57.129.115.159` | | `SSH_IDENTITY_FILE_WINDOWS` | `$env:USERPROFILE\.ssh\id_ed25519` | | `SSH_BATCH_MODE` | `true` | | `SSH_READY_COMMAND` | `ssh -i "$env:USERPROFILE\.ssh\id_ed25519" -o IdentitiesOnly=yes -o BatchMode=yes ubuntu@57.129.115.159 "echo OK"` | | `SSH_READY_EXPECTED_OUTPUT` | `OK` | | `SSH_NOT_READY_STATE` | `blocked` | Règle : ```text Avant tout bouton serveur, l’app doit exécuter un test SSH non interactif. ``` Si le test ne retourne pas exactement : ```text OK ``` l’app doit bloquer : ```text Pull serveur Dry-run categories serveur Apply categories serveur Purger caches serveur Toute action distante avec sudo ``` Message utilisateur : ```text SSH non prêt. Corriger l’accès SSH avant d’utiliser les actions serveur. ``` --- ## 5. Règle SSH anti-gel Le GUI ne doit jamais masquer une demande SSH ou sudo invisible. Interdit : ```text lancer une commande distante pouvant demander un mot de passe lancer une commande SSH sans BatchMode pour une action automatisée afficher seulement “en cours” sans sortie brute bloquer l’interface sans journal visible ``` Obligatoire : ```text précheck SSH journal visible statut final explicite commande copiée si action manuelle requise blocage des boutons dépendants en cas d’échec ``` --- ## 6. Variables canoniques — seed | Variable | Valeur canonique | Règle | |---|---|---| | `SEED_TOOL_COMPONENT` | `tool_uckkseed` | Composant Moodle du seed. | | `SEED_DEFAULTMODE_SETTING` | `tool_uckkseed/defaultmode` | Configuration Moodle qui contrôle le mode réel. | | `SEED_SAFE_MODE` | `dry_run` | Mode sûr par défaut. | | `SEED_APPLY_MODE` | `apply` | Mode temporaire pour écriture réelle. | | `SEED_FORCE_ALONE_APPLIES` | `false` | `--force` seul ne garantit pas l’écriture. | | `SEED_CLI_ACCEPTS_MODE_OPTION` | `false` | `--mode=apply` n’est pas accepté par le CLI actuel. | | `SEED_APPLY_PATTERN` | `set_config apply → seed --force → set_config dry_run` | Séquence obligatoire. | Règle : ```text Le seed réel vient de defaultmode, pas seulement de --force. ``` --- ## 7. Workflow seed canonique Séquence obligatoire pour appliquer un preset : ```text 1. Vérifier SSH 2. Git pull serveur 3. Dry-run seed 4. Changer defaultmode à apply 5. Lancer seed.php avec --force 6. Remettre defaultmode à dry_run 7. Purger caches 8. Vérifier visuellement ou par smoke test ``` Règle de jonction : ```text Ne pas aller à l’étape apply si le dry-run échoue. Ne pas quitter après apply sans remettre defaultmode à dry_run. Ne pas considérer l’opération terminée avant purge cache. ``` --- ## 8. Commandes seed canoniques ### 8.1 Lire / définir `defaultmode=apply` ```bash cd /var/www/moodle/public sudo -u www-data php <<'PHP' > ~/.ssh/authorized_keys && chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys" ``` Après exécution, refaire : ```powershell ssh -i "$env:USERPROFILE\.ssh\id_ed25519" -o IdentitiesOnly=yes -o BatchMode=yes ubuntu@57.129.115.159 "echo OK" ``` --- ## 15. Encodage PowerShell Problème observé : ```text Vérifier chemins Sync source → Moodle local ``` Cause probable : ```text .ps1 lu comme ANSI par Windows PowerShell ``` Correction canonique : ```powershell $path = "C:\mycode\UCKK\uckk-moodle\tools\uckk-ops\uckk_ops_gui.ps1" $bytes = [System.IO.File]::ReadAllBytes($path) $text = [System.Text.Encoding]::UTF8.GetString($bytes) $utf8bom = New-Object System.Text.UTF8Encoding($true) [System.IO.File]::WriteAllText($path, $text, $utf8bom) ``` Règle : ```text Les scripts GUI PowerShell doivent être sauvegardés en UTF-8 avec BOM ou exécutés avec PowerShell 7. ``` --- ## 16. Journalisation minimale Chaque action GUI doit écrire : ```text timestamp action name preconditions command summary raw output parsed status next recommended step cleanup status ``` Exemple : ```text [2026-06-01 17:22:00] Apply categories SSH: ready Seed defaultmode before: dry_run Set defaultmode: apply Seed result: completed, failed=0, errors=0 Set defaultmode: dry_run Next: purge caches ``` --- ## 17. Smoke tests canoniques | Test | URL / commande | Résultat attendu | |---|---|---| | `SMOKE_COURSE_INDEX` | `https://uckk.org/course/index.php` | Catégories publiques visibles. | | `SMOKE_MOODLE_HOME` | `https://uckk.org/` | Moodle répond. | | `SMOKE_SSH` | `ssh ... "echo OK"` | `OK`. | | `SMOKE_CACHE_PURGE` | commande purge détectée | exit code 0. | Règle : ```text Un seed réussi sans smoke test reste “completed, verification pending”. ``` --- ## 18. Règles de sécurité opérationnelle Interdit : ```text laisser defaultmode=apply après une opération masquer une commande sudo interactive lancer un apply sans dry-run réussi lancer un apply si SSH n’est pas prêt supposer que public/admin/cli/purge_caches.php existe confondre registry JSON et plugin runtime présenter un git pull comme preuve que Moodle DB est à jour ``` Obligatoire : ```text dry_run par défaut apply temporaire seulement cleanup automatique journal visible préconditions explicites smoke test final ``` --- ## 19. États finaux valides Un cycle categories est complet seulement si : ```text SSH fonctionnel = oui Git pull serveur = oui Dry-run categories = completed, errors 0 Apply categories = completed, errors 0 Seed defaultmode remis à dry_run = oui Purge caches = oui Smoke test = passed ou vérification manuelle demandée ``` Si une étape échoue : ```text ne pas déclarer l’opération complète afficher l’étape bloquante afficher la commande ou sortie utile proposer la prochaine jonction, pas toute la suite ``` --- ## 20. Relation avec `academic_registry_json` Variables : | Variable | Valeur | |---|---| | `ACADEMIC_REGISTRY_RUNTIME_COMPONENT` | `false` | | `ACADEMIC_REGISTRY_IS_SOURCE_ONLY` | `true` | | `ACADEMIC_REGISTRY_APPLY_METHOD` | `tool_uckkseed` | Règle : ```text academic_registry_json n’est pas un composant runtime Moodle. Il ne doit pas être traité comme local_uckk, mod_uckkarchive, theme_uckk ou tool_uckkseed. ``` Flux correct : ```text modifier academic_registry_json/categories.json → git commit + push → git pull serveur → seed categories → purge caches → vérifier dans Moodle ``` --- ## 21. Relation avec les plugins Moodle Les plugins Moodle doivent être synchronisés dans le runtime Moodle : ```text local/uckk mod/uckkarchive theme/uckk admin/tool/uckkseed ``` Le registre académique JSON reste source-only : ```text academic_registry_json ``` Règle : ```text L’app doit avoir des actions distinctes pour : - sync plugin runtime - seed registry data - purge cache - smoke test ``` --- ## 22. Messages utilisateur canoniques SSH non prêt : ```text SSH non prêt. Corriger l’accès SSH avant d’utiliser les actions serveur. ``` Dry-run requis : ```text Le dry-run doit réussir avant l’application réelle. ``` Mode seed dangereux : ```text Le seed est encore en mode apply. Remise en dry_run requise avant de continuer. ``` Purge introuvable : ```text Aucun purge_caches.php trouvé dans les chemins connus. ``` Succès seed : ```text Seed complété. Mode safe restauré. Purge caches requise. ``` Succès final : ```text Opération complétée. Vérifier visuellement Moodle si le smoke test n’a pas été automatisé. ``` --- ## 23. Tests obligatoires Tests unitaires / fonctionnels : ```text SSH ready parser accepts exact OK SSH ready parser rejects empty output server buttons disabled when SSH blocked apply button disabled when dry-run failed apply flow sets defaultmode=apply apply flow restores defaultmode=dry_run apply flow flags cleanup_required if restore fails cache purge selects fallback path when public path missing registry JSON is classified source-only plugin paths are classified runtime components PowerShell encoding check warns on broken accents ``` Tests de non-régression : ```text --force alone is not treated as apply guarantee --mode=apply is not emitted for current CLI git pull is not treated as DB update cache purge path is detected, not hardcoded only ``` --- ## 24. Anti-dérive finale Ces noms sont définitifs : ```text Repo source Runtime Moodle DB Moodle defaultmode dry_run apply SSH ready seed categories purge caches smoke test academic_registry_json source-only registry ``` Noms à éviter : ```text sync DB deploy JSON directly apply with --mode force apply runtime registry component Moodle source DB ``` Règle : ```text Ne pas utiliser un nom qui laisse croire qu’un fichier JSON source est automatiquement visible dans Moodle. Ne pas utiliser un nom qui laisse croire que --force suffit pour écrire. ``` --- ## 25. Résumé exécutable ```text Avant serveur : vérifier SSH en BatchMode. Avant apply : dry-run réussi. Pour apply : passer defaultmode à apply, lancer seed --force, remettre defaultmode à dry_run. Après apply : purger caches avec détection de chemin. Après purge : smoke test ou vérification visuelle. Toujours distinguer repo source, runtime Moodle et DB Moodle. ``` --- ## 26. État cible de l’app L’app d’opérations UCKK doit permettre à l’utilisateur de savoir clairement : ```text ce qui existe dans Git ce qui est synchronisé dans Moodle ce qui a été écrit dans la DB Moodle si SSH est prêt si le seed est safe si les caches sont purgés quelle étape vient ensuite quelle commande a réellement tourné ``` Final rule : ```text L’app doit réduire l’ambiguïté opérationnelle. Elle ne doit jamais cacher une attente interactive, un mode dangereux ou une différence entre source, runtime et DB. ``` ================================================================================================ FILE: mod/uckkarchive/docs/_alignment_variables.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 1e0f66fab706b44261ac6c67c33aaddfdec69637012a622b61765aecbdb3ce63 CONTENT_BYTES: 26378 ================================================================================================ # UCKK Archive — Shared Documentation Variables **Path:** `docs/_alignment_variables.md` **Component:** `mod_uckkarchive` **Purpose:** Canonical variables for generating the clean final-state documentation set across separate conversations. **Use:** Paste this file at the beginning of every document-generation conversation. --- ## 1. Documentation mode ```text DOC_MODE = final_state_specification DOC_STYLE = descriptive DOC_HISTORY = forbidden DOC_GAPS = forbidden DOC_ACCEPTANCE_CHECKLIST = forbidden DOC_RELEASE_NOTES = forbidden DOC_TARGET = build-ready module specification ``` Rules: ```text Do not write historical narrative. Do not keep gap registers. Do not write acceptance checklists. Do not write release notes. Do not describe old decisions as alternatives. Do not say "future optional" for required target features. Describe only the final target architecture to be coded. ``` --- ## 2. Plugin identity ```text PLUGIN_NAME = UCKK Archive PLUGIN_TYPE = mod PLUGIN_FOLDER = uckkarchive MOODLE_COMPONENT = mod_uckkarchive MOODLE_PLUGIN_PATH = mod/uckkarchive ``` Canonical paths: ```text SOURCE_DOCS_PATH = C:\mycode\UCKK\uckk-moodle\mod\uckkarchive\docs ACTIVE_MOODLE_DOCS_PATH = C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive\docs SOURCE_PLUGIN_PATH = C:\mycode\UCKK\uckk-moodle\mod\uckkarchive ACTIVE_MOODLE_PLUGIN_PATH = C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive ``` --- ## 3. Core architecture formula ```text ARCHITECTURE_FORMULA = Moodle-native on the outside, self-contained archive/media/content-advisory system on the inside. ``` Canonical module definition: ```text mod_uckkarchive = self-contained Moodle activity module for archive memory, media library management, and content advisory governance. ``` The module owns internally: ```text archive records archive items media records media versions media files media collections media collection membership media relations media tags proof records Kristals provenance records revision history validation state restricted archive metadata restricted media metadata content advisory tags cultural sensitivity tags content tag sets content markers content reviews external works foreign media references media source records audience suitability rules export packages export manifests ``` The module uses Moodle for: ```text plugin lifecycle course module context users roles capabilities groups File API Privacy API Backup API Restore API External Services API events settings language strings rendering scheduled tasks ``` --- ## 4. Boundary variables ```text GRADE_OWNER = Moodle gradebook REGISTRY_OWNER = local_uckk CHALLENGE_OWNER = mod_uckkchallenge ASSEMBLY_OWNER = mod_uckkassembly INTEGRITY_OWNER = tool_uckkintegrity REPORT_OWNER = report_uckk ARCHIVE_OWNER = mod_uckkarchive ``` Boundary rules: ```text mod_uckkarchive does not own grades. mod_uckkarchive does not own transcripts. mod_uckkarchive does not own enrolment authority. mod_uckkarchive does not own administrative academic registry authority. mod_uckkarchive may reference challenge ids, assembly ids, integrity case ids, course ids, and competency ids. mod_uckkarchive must degrade gracefully when optional owner plugins are not installed. ``` Optional integration variables: ```text OPTIONAL_CHALLENGE_COMPONENT = mod_uckkchallenge OPTIONAL_ASSEMBLY_COMPONENT = mod_uckkassembly OPTIONAL_INTEGRITY_COMPONENT = tool_uckkintegrity OPTIONAL_REPORT_COMPONENT = report_uckk ``` No hard dependency rule: ```text No install-time hard dependency on mod_uckkchallenge, mod_uckkassembly, tool_uckkintegrity, or report_uckk. ``` --- ## 5. Active documentation set Use this clean final-state documentation set: ```text docs/00_index.md docs/01_architecture_decision.md docs/02_domain_boundaries.md docs/03_file_architecture.md docs/04_data_model.md docs/05_media_library.md docs/06_file_api_and_storage.md docs/07_permissions_and_roles.md docs/08_archive_workflows.md docs/09_media_workflows.md docs/10_provenance_versioning_validation.md docs/11_privacy_retention_redaction.md docs/12_backup_restore.md docs/13_services_and_ajax_api.md docs/14_events_and_audit.md docs/15_ui_templates_and_amd.md docs/16_integration_with_courses.md docs/17_integration_with_challenges.md docs/18_integration_with_assemblies.md docs/19_integration_with_integrity.md docs/20_reporting_and_exports.md docs/21_testing_strategy.md docs/22_installation.md docs/23_upgrade.md docs/24_release_spec.md docs/25_mediatheque_public_explorer.md ``` Do not generate these old/process files: ```text docs/05_media_database_division.md docs/09_didactic_material_workflows.md docs/24_acceptance_checklist.md docs/25_known_gaps_and_corrections.md docs/26_release_notes.md docs/27_file_architecture_manifest.md ``` Documentation-set rule: ```text docs/25_mediatheque_public_explorer.md defines the public Médiathèque façade. It does not define a second internal media-library engine. ``` --- ## 6. Root file architecture Required root files: ```text version.php lib.php locallib.php mod_form.php view.php index.php media.php export.php item.php styles.css settings.php README.md ``` Root rule: ```text Root PHP files are controllers, integration hooks, or Moodle entry points. Domain logic belongs in classes/local. Output shaping belongs in classes/output. AJAX/external contracts belong in classes/external. ``` --- ## 7. Database tables Canonical table prefix: ```text TABLE_PREFIX = uckkarchive_ ``` Required core tables: ```text uckkarchive uckkarchive_item uckkarchive_proof uckkarchive_revision uckkarchive_validation uckkarchive_kristal uckkarchive_export ``` Required media tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_file uckkarchive_media_collection uckkarchive_media_collection_item uckkarchive_media_relation uckkarchive_media_tag uckkarchive_media_source ``` Required content advisory tables: ```text uckkarchive_content_tag uckkarchive_content_tag_set uckkarchive_content_marker uckkarchive_content_review uckkarchive_external_work ``` Database rules: ```text All tables must have id as primary key. All portable objects must have uuid where applicable. All human-created mutable tables must have timecreated and timemodified. All user-authored tables must have userid or createdby/modifiedby where relevant. ``` UUID rule: ```text Archive objects, media objects, content markers, external works, and export packages use UUIDs for export, restore, duplication, and cross-site portability. ``` --- ## 8. Capabilities Canonical archive capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Canonical media capabilities: ```text mod/uckkarchive:viewmedia mod/uckkarchive:addmedia mod/uckkarchive:editmedia mod/uckkarchive:deletemedia mod/uckkarchive:downloadmedia mod/uckkarchive:versionmedia mod/uckkarchive:managemediacollections mod/uckkarchive:exportmedia mod/uckkarchive:viewrestrictedmedia ``` Canonical content advisory capabilities: ```text mod/uckkarchive:viewadvisories mod/uckkarchive:manageadvisories mod/uckkarchive:reviewadvisories mod/uckkarchive:viewculturallyrestricted mod/uckkarchive:manageexternalworks ``` Capability rules: ```text Capabilities are gates, not full authority. Policy classes still enforce context, ownership, visibility, status, validation state, restricted state, content advisory rules, cultural protocol rules, retention, and redaction. ``` Removed capability: ```text mod/uckkarchive:versionitem = not used ``` Versioning permissions: ```text archive item revision = mod/uckkarchive:reviseitem media versioning = mod/uckkarchive:versionmedia ``` --- ## 9. File API areas Component: ```text FILE_COMPONENT = mod_uckkarchive ``` Canonical archive file areas: ```text intro item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` Canonical media file areas: ```text media_original media_preview media_thumbnail media_derivative media_caption media_transcript media_attachment ``` Canonical content advisory file areas: ```text content_review_files external_work_reference_files cultural_protocol_files ``` File area rule: ```text classes/local/file_area_registry.php is the central file-area registry. All controllers, services, pluginfile handling, privacy provider, backup, restore, and tests must use the registry. ``` Forbidden storage: ```text No production archive/media files in unmanaged public folders. No binary media files directly in custom database fields. No direct public file URLs as authority. ``` --- ## 10. Media lifecycle Canonical media states: ```text draft submitted active restricted superseded archived deleted_soft ``` Media lifecycle rule: ```text File existence is not media availability. Media status controls usability. Visibility controls access. Policy controls download and export. Content advisories describe suitability, cultural protocol, and access conditions. Retention controls deletion. ``` --- ## 11. Archive item statuses Canonical archive item statuses: ```text draft submitted under_review validated published restricted contested invalidated superseded archived ``` --- ## 12. Validation states Canonical validation states: ```text unverified human_reviewed verified contested invalidated archived ``` Validation rules: ```text Validation is human-final. AI cannot validate archive records. AI cannot invalidate archive records. AI cannot close contestations. AI cannot approve cultural protocol access. ``` --- ## 13. Visibility values Canonical visibility values: ```text private user group course cohort program institution public restricted restricted_integrity restricted_cultural ``` Compatibility rule: ```text institutional must normalize to institution. ``` --- ## 14. Provenance values Canonical provenance values: ```text human ai_assisted imported system archive assembly challenge integrity media external_work content_review ``` Provenance rule: ```text Provenance explains origin. Provenance does not grant authority by itself. ``` --- ## 15. Media relation types Canonical media relation types: ```text belongs_to_item belongs_to_kristal belongs_to_collection is_derivative_of is_translation_of is_excerpt_of is_proof_for is_source_for replaces references duplicates references_external_work contains_content_marker ``` Relation rule: ```text Relations describe media graph meaning. Relations do not transfer ownership to external plugins or external rights holders. ``` --- ## 16. Content advisory subsystem Canonical subsystem name: ```text CONTENT_ADVISORY_SYSTEM = content advisories, cultural sensitivity tags, content markers, external works, reviews, and audience suitability rules ``` User-facing wording: ```text content advisory content warning cultural advisory cultural protocol audience suitability ``` Avoid using `trigger` alone as the database/system name because it can be confused with database triggers. Allowed user-facing phrase: ```text trigger warning ``` Architecture rule: ```text A content advisory does not ban the media. It describes conditions for responsible access, teaching, warning, review, restriction, or contextualization. ``` Content advisory tag examples: ```text sexual_violence violence racism colonial_violence death self_harm substance_use nudity explicit_language culturally_sensitive sacred_content ceremonial_content restricted_knowledge grief_or_mourning requires_context not_for_children ``` Cultural protocol tag examples: ```text culturally_sensitive sacred_content ceremonial_content restricted_knowledge community_permission_required elder_review_required seasonal_or_contextual_access not_for_public_export not_for_children requires_context ``` Audience suitability values: ```text general guided mature restricted restricted_cultural restricted_integrity staff_only ``` Content advisory severity values: ```text notice moderate strong restricted ``` Content advisory review states: ```text draft pending_review reviewed approved contested retired ``` Content tag set rule: ```text uckkarchive_content_tag_set groups advisory tags into reusable vocabularies. Examples: general_advisories, cultural_protocols, classroom_suitability, integrity_sensitive, youth_access. ``` Content review rule: ```text uckkarchive_content_review records human review of content markers, advisory tags, cultural protocol notes, suitability, and restriction decisions. AI may suggest tags or markers, but human review is required before advisory status becomes approved. ``` --- ## 17. Content markers and locators Canonical content marker table: ```text uckkarchive_content_marker ``` Content marker purpose: ```text Link a content advisory or cultural protocol tag to a precise location inside an internal media object, archive item, or external work. ``` Canonical locator types: ```text timecode timecode_range page page_range chapter chapter_range section section_range paragraph paragraph_range scene track timestamp url_fragment manual_reference ``` Canonical locator examples: ```text Movie Maïna -> sexual_violence -> 01:12:30-01:15:10 Book The Body Keeps the Score -> sexual_violence -> page 42-45 PDF -> culturally_sensitive -> page 7 Audio -> grief_or_mourning -> 00:08:12-00:09:40 Website -> colonial_violence -> url_fragment #section-3 ``` Content marker rule: ```text A content marker can point to internal media, archive items, media versions, external works, or manual references. A content marker must include enough locator information to be useful without storing unauthorized copies of external content. ``` --- ## 18. External works and foreign media Canonical external work table: ```text uckkarchive_external_work ``` External work purpose: ```text Represent works not produced by UCKK that may be referenced, taught, reviewed, tagged, or connected to archive/media records. ``` External work types: ```text film book article podcast website external_video external_image public_archive_item third_party_pdf other ``` Canonical media source table: ```text uckkarchive_media_source ``` Media source values: ```text produced_by_uckk submitted_to_uckk imported external_reference_only licensed_external public_domain fair_use_reference restricted_reference ``` Source ownership values: ```text uckk_created uckk_commissioned member_submitted partner_submitted external_reference third_party_copyright public_domain open_license unknown_source ``` External/foreign media rule: ```text The archive may reference foreign media without copying it. The archive may store metadata, content advisories, cultural protocol notes, teaching notes, locators, and references for external works. The archive must not imply ownership over third-party works. ``` --- ## 18.1 Public Médiathèque surface Canonical public surface variables: ```text PUBLIC_MEDIATHEQUE_PAGE_NAME = Médiathèque PUBLIC_MEDIATHEQUE_PAGE_KEY = mediatheque PUBLIC_MEDIATHEQUE_EXPLORER_NAME = Explorateur Médiathèque PUBLIC_MEDIATHEQUE_EXPLORER_KEY = mediatheque_explorer PUBLIC_MEDIATHEQUE_ROUTE = /local/uckk/mediatheque.php PUBLIC_MEDIATHEQUE_SURFACE_COMPONENT = local_uckk PUBLIC_MEDIATHEQUE_DATA_COMPONENT = mod_uckkarchive PUBLIC_MEDIATHEQUE_SERVICE = mod_uckkarchive_search_mediatheque PUBLIC_MEDIATHEQUE_SITEWIDE_ARCHIVEID = 0 PUBLIC_MEDIATHEQUE_SITEWIDE_CMID = 0 ``` Canonical architecture rule: ```text Médiathèque = public page. Explorateur Médiathèque = public search/filter/navigation component. mod_uckkarchive = media data owner and policy authority. local_uckk = public shell, route, page rendering and navigation. ``` Canonical runtime flow: ```text local/uckk/mediatheque.php → local_uckk public page shell → local/uckk/amd/src/mediatheque_explorer.js → mod_uckkarchive_search_mediatheque → classes/local/public_mediatheque_service.php → classes/local/public_mediatheque_repository.php → existing media tables and policies ``` Public scope rule: ```text cmid > 0 = module-scoped public search. archiveid > 0 = archive-scoped public search. cmid = 0 and archiveid = 0 = site-wide public search. ``` Public DTO envelope: ```text context filters facets items pagination notices warnings empty ``` Public item DTO: ```text uuid objecttype title subtitle summary mediatype mimetype language thumbnailurl detailurl source rights status visibility validation badges advisories culturalprotocol relations actions ``` Public safety rule: ```text The public Médiathèque never exposes original files, private notes, cultural protocol notes, raw metadata, review rationale, provenance hashes, integrity case ids, or internal database identifiers. ``` Public reuse rule: ```text Do not create a second media-library engine. Do not create mediatheque_card.mustache, mediatheque_detail.mustache, mediatheque_marker.mustache, get_mediatheque_item.php, get_mediatheque_filters.php, or get_mediatheque_collection.php unless the public contract explicitly changes. Reuse the existing media library domain, templates, cards, advisories, collections and policies. ``` --- ## 19. Export manifest Canonical manifest filename: ```text manifest.json ``` Manifest includes: ```text plugin component archive id export id export timestamp export actor export reason archive item ids media uuids media version uuids external work uuids content marker uuids content tag keys content tag set keys content review state file hashes file sizes mime types visibility restricted flags audience suitability cultural protocol flags provenance relations collections tags redaction level validation state revision history ``` Export rule: ```text Exports are portable and explainable. Exports do not bypass permissions, visibility, retention, redaction, cultural protocol restrictions, or content advisory policy. ``` --- ## 20. Required classes/local files ```text classes/local/archive_item.php classes/local/archive_policy.php classes/local/content_marker.php classes/local/content_policy.php classes/local/content_review.php classes/local/content_tag.php classes/local/content_tag_set.php classes/local/context_resolver.php classes/local/export_package.php classes/local/external_work.php classes/local/file_area_registry.php classes/local/kristal.php classes/local/manifest_builder.php classes/local/media.php classes/local/media_collection.php classes/local/media_file.php classes/local/media_policy.php classes/local/media_relation.php classes/local/media_search.php classes/local/media_source.php classes/local/media_tag.php classes/local/media_version.php classes/local/metadata_validator.php classes/local/proof.php classes/local/provenance.php classes/local/public_mediatheque_repository.php classes/local/public_mediatheque_service.php classes/local/revision.php classes/local/uuid.php ``` Local rule: ```text classes/local is the authority layer for archive/media/content-advisory behavior. public_mediatheque_repository.php and public_mediatheque_service.php are public façade adapters, not a second media engine. ``` --- ## 21. Required external service files ```text classes/external/get_content_tags.php classes/external/get_content_tag_sets.php classes/external/get_content_markers.php classes/external/add_content_marker.php classes/external/update_content_marker.php classes/external/delete_content_marker.php classes/external/review_content_marker.php classes/external/get_external_works.php classes/external/get_external_work.php classes/external/add_external_work.php classes/external/update_external_work.php classes/external/search_mediatheque.php ``` Service rule: ```text Content advisory services must check context, capability, visibility, cultural protocol restrictions, review state, and redaction rules. search_mediatheque.php is the single public Médiathèque AJAX endpoint. search_mediatheque.php delegates to public_mediatheque_service.php and does not implement media search logic directly. ``` --- ## 22. Required database files ```text db/access.php db/events.php db/install.xml db/services.php db/tasks.php db/upgrade.php ``` Database rule: ```text db/install.xml defines the full current target schema. db/upgrade.php migrates existing installs to the current target schema. ``` --- ## 23. Required form files ```text classes/form/archive_item_form.php classes/form/content_marker_form.php classes/form/content_review_form.php classes/form/content_tag_form.php classes/form/export_form.php classes/form/external_work_form.php classes/form/kristal_form.php classes/form/media_collection_form.php classes/form/media_form.php classes/form/media_relation_form.php classes/form/media_version_form.php classes/form/validation_form.php ``` Form rule: ```text Forms collect and shape input. Policy remains in classes/local. ``` --- ## 24. Required output and template files Required output files: ```text classes/output/archive_item_card.php classes/output/archive_view.php classes/output/content_advisory_panel.php classes/output/external_work_card.php classes/output/kristal_card.php classes/output/media_card.php classes/output/media_collection.php classes/output/media_library.php classes/output/media_version_list.php classes/output/provenance_panel.php classes/output/renderer.php ``` Required template files: ```text templates/archive_item_card.mustache templates/archive_view.mustache templates/content_advisory_panel.mustache templates/external_work_card.mustache templates/kristal_card.mustache templates/media_card.mustache templates/media_collection.mustache templates/media_library.mustache templates/media_relation_list.mustache templates/media_upload.mustache templates/media_version_list.mustache templates/proof_card.mustache templates/provenance_panel.mustache templates/validation_panel.mustache ``` Template rule: ```text Templates receive pre-filtered render data. Templates do not enforce authority. ``` --- ## 25. Required AMD files ```text amd/src/archive.js amd/src/content_advisory.js amd/src/export.js amd/src/external_work.js amd/src/kristal.js amd/src/media.js amd/src/media_collection.js amd/build/archive.min.js amd/build/content_advisory.min.js amd/build/export.min.js amd/build/external_work.min.js amd/build/kristal.min.js amd/build/media.min.js amd/build/media_collection.min.js ``` AMD rule: ```text amd/src is source. amd/build is generated. AMD modules do not authorize access. ``` --- ## 26. Required event classes ```text classes/event/archive_viewed.php classes/event/archive_item_created.php classes/event/archive_item_validated.php classes/event/archive_item_revised.php classes/event/archive_item_exported.php classes/event/media_created.php classes/event/media_updated.php classes/event/media_version_created.php classes/event/media_collection_created.php classes/event/media_exported.php classes/event/content_marker_created.php classes/event/content_marker_reviewed.php classes/event/external_work_created.php ``` Event rule: ```text Events audit successful state changes. Events must not expose restricted content, raw content, private cultural protocol notes, or redacted details. ``` --- ## 27. Required task files ```text classes/task/generate_archive_exports.php classes/task/generate_media_derivatives.php classes/task/generate_media_thumbnails.php classes/task/purge_expired_exports.php classes/task/rebuild_media_search.php classes/task/rebuild_content_marker_index.php classes/task/validate_pending_items.php ``` Task rule: ```text Scheduled tasks reuse classes/local domain logic. Scheduled tasks do not bypass policy checks for generated outputs. ``` --- ## 28. Required test files ```text tests/archive_test.php tests/backup_restore_test.php tests/content_advisory_test.php tests/export_test.php tests/external_work_test.php tests/file_api_test.php tests/lib_test.php tests/media_library_test.php tests/privacy_provider_test.php tests/services_test.php tests/public_mediatheque_repository_test.php tests/public_mediatheque_service_test.php tests/external/search_mediatheque_test.php tests/behat/uckkarchive.feature tests/behat/uckkarchive_media.feature tests/behat/uckkarchive_content_advisory.feature ``` Testing rule: ```text Tests verify the final target behavior, not historical transitions. Public Médiathèque tests verify the public façade contract only. They do not duplicate the internal media-library engine tests. ``` --- ## 29. Writing instructions for every generated doc Each document must: ```text describe final target behavior use the variables in this file avoid historical framing avoid gap language avoid acceptance checklist language avoid release notes language avoid "future optional" for required media-library architecture avoid "future optional" for content advisory architecture use consistent table names use consistent capabilities use consistent file areas use consistent plugin boundaries use content advisory terminology consistently include cultural protocol handling where relevant include external/foreign media handling where relevant distinguish public Médiathèque façade from internal media-library engine use search_mediatheque.php only as the public AJAX endpoint state that local_uckk renders the public page and mod_uckkarchive owns media data and policies ``` Each document must not include: ```text known gaps known corrections acceptance checklist release notes old architecture debate media as only generic item attachment content advisories as only a JSON field versionitem capability hard dependency on tool_uckkintegrity a second Médiathèque media engine duplicated mediatheque_card or mediatheque_detail templates duplicated get_mediatheque_item, get_mediatheque_filters, or get_mediatheque_collection services authorization decisions in AMD or Mustache ``` --- ## 30. Standard final sentence Every generated document may end with a variant of this rule: ```text This document defines the final target behavior for implementation. Code, tests, services, UI, backup/restore, privacy, content advisory governance, and packaging must conform to this specification. ``` ================================================================================================ FILE: mod/uckkarchive/README.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: ffaedd3b7d9527f91ca6c53e784441f1356d3dde810a84e8734d37eb16b4e3bd CONTENT_BYTES: 12171 ================================================================================================ # UCKK Archive `mod_uckkarchive` is the Moodle activity module responsible for UCKK archive memory, didactic material, evidence preservation, provenance, validation, revision history, restricted archive records, Kristals, portfolio items, and exportable archive packages. This module is part of the UCKK-Moodle implementation. --- ## Location Development location in the active Moodle instance: ```text C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive ```` Distribution / source location: ```text C:\mycode\UCKK\uckk-moodle\mod\uckkarchive ``` Plugin type: ```text mod_uckkarchive ``` Moodle plugin path: ```text mod/uckkarchive ``` --- ## Purpose UCKK Archive owns the archive domain. It stores and manages: * didactic material; * media-linked archive items; * evidence and proof files; * course work records; * challenge result records; * Assembly minutes and preserved decisions; * Kristals; * portfolio items; * integrity summaries; * version records; * provenance trails; * validation state; * restricted archive metadata; * exportable archive packages. The archive is not a gradebook, not an administrative registry, and not the owner of Assembly or integrity workflows. --- ## Architectural decision The accepted division is: ```text mod_uckkarchive = didactic material, archive items, evidence, media, provenance Moodle gradebook = grades, grade items, grade reports local_uckk = shared UCKK registry and institutional structure tool_uckkintegrity = integrity procedures and case workflow mod_uckkassembly = motions, deliberations, Assembly decisions report_uckk = reporting and institutional exports ``` UCKK Archive may preserve records from those systems, but it does not own their authority. --- ## Domain boundaries `mod_uckkarchive` owns: * archive activity instances; * archive items; * proof packages; * Kristals; * provenance records; * revision records; * validation history; * visibility state; * restricted archive records; * archive exports. `mod_uckkarchive` does not own: * global UCKK registry permissions; * course-format display rules; * challenge workflow authority; * Assembly workflow authority; * integrity case authority; * reporting authority; * gradebook ownership; * administrative procedures. --- ## Storage model The module uses Moodle database tables for metadata and Moodle File API for files. Files must not be stored in arbitrary public folders such as: ```text public/media public/uckk_media public/db_media ``` Files belong in Moodle file areas attached to the `mod_uckkarchive` component. Canonical component: ```text mod_uckkarchive ``` Recommended file areas: ```text item_content item_publicsummary item_files proof_files decision_attachments minutes_files kristal_files portfolio_files integrity_exports provenance_files validation_files revision_files export_package export_manifest ``` --- ## Current data model Current archive tables include: ```text uckkarchive uckkarchive_item uckkarchive_kristal uckkarchive_proof uckkarchive_prov uckkarchive_rev uckkarchive_export ``` These tables currently represent the archive, evidence, Kristal, provenance, revision, and export layers. --- ## Media database decision Didactic material and media must remain separate from grades and administrative procedures. Current implementation stores media-like material through archive items and attached file areas. Accepted current interpretation: ```text uckkarchive_item = generic archive / media / didactic resource object ``` Future optional refinement: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation ``` This refinement should be added only if media-specific behavior becomes too large to remain inside `uckkarchive_item`. --- ## Archive item types Common archive item types include: ```text proof decision course_work challenge_result assembly_minutes integrity_case_summary kristal reflection portfolio_item version_record ``` --- ## Status values Archive items may move through workflow states such as: ```text draft submitted under_review validated published restricted contested invalidated superseded archived ``` --- ## Visibility values Archive visibility is controlled separately from Moodle course visibility. Common visibility values include: ```text private course cohort program institution institutional public restricted_integrity ``` Restricted records require dedicated capability checks and service-layer policy enforcement. --- ## Provenance values Archive records may declare provenance such as: ```text human ai_assisted imported system archive assembly challenge integrity ``` Provenance is part of the archive record and should be preserved through revisions, exports, backup, restore, and privacy workflows. --- ## Capabilities The module defines archive-specific Moodle capabilities: ```text mod/uckkarchive:addinstance mod/uckkarchive:view mod/uckkarchive:additem mod/uckkarchive:validateitem mod/uckkarchive:reviseitem mod/uckkarchive:viewrestricted mod/uckkarchive:export ``` Capabilities are permission gates only. They do not bypass archive policy, ownership rules, validation state, visibility rules, retention policy, privacy requirements, or restricted-record safeguards. --- ## Main pages Root activity pages include: ```text index.php view.php add.php item.php validate.php export.php mod_form.php settings.php lib.php locallib.php version.php ``` Typical flow: ```text view.php → archive overview add.php → create archive item item.php → view archive item validate.php → validate or revise archive item export.php → prepare archive export ``` --- ## Services The module exposes external/AJAX services for archive interactions. Current service areas include: ```text get_archive get_archive_items get_archive_item get_archive_item_card get_proofs get_provenance_panel get_kristal get_revisions get_restricted_item save_item_draft add_item add_proof update_provenance validate_item revise_item create_kristal update_kristal get_export_preview export_items get_export_status ``` Server-side services must always enforce Moodle login, context, capability, ownership, visibility, validation, provenance, and restriction checks. --- ## Events The module includes archive events such as: ```text archive_viewed archive_item_created archive_item_validated archive_item_revised archive_item_exported ``` Events are used for auditability, reporting, traceability, and Moodle event integration. --- ## UI The module uses Moodle templates and AMD modules. Templates include: ```text templates/archive_view.mustache templates/archive_item_card.mustache templates/proof_card.mustache templates/provenance_panel.mustache templates/validation_panel.mustache templates/kristal_card.mustache ``` AMD modules include: ```text amd/src/archive.js amd/src/export.js amd/src/kristal.js ``` Client-side JavaScript is UI-only. It must not authoritatively validate records, expose restricted items, revise archive history, export files, open integrity cases, or replace server-side capability checks. --- ## Privacy The module includes: ```text classes/privacy/provider.php ``` The privacy provider must cover: * archive items; * proof records; * Kristals; * provenance; * revisions; * exports; * user-linked metadata; * file areas; * restricted archive records; * validation records. Archive privacy logic must support export, deletion, redaction, and retention rules according to Moodle privacy API requirements and UCKK institutional policy. --- ## Backup and restore The module includes Moodle backup and restore support: ```text backup/moodle2/backup_uckkarchive_activity_task.class.php backup/moodle2/backup_uckkarchive_stepslib.php backup/moodle2/restore_uckkarchive_activity_task.class.php backup/moodle2/restore_uckkarchive_stepslib.php ``` Backup/restore must preserve: * activity instance data; * archive items; * proofs; * Kristals; * provenance; * revisions; * exports; * validation state; * restricted metadata; * file areas. File area names must remain consistent between controllers, forms, services, output classes, privacy provider, backup, restore, and tests. --- ## Tests The module includes PHPUnit and Behat tests: ```text tests/archive_test.php tests/lib_test.php tests/behat/uckkarchive.feature ``` Tests should cover: * canonical statuses; * canonical visibility values; * archive policy helpers; * restricted item access; * file area handling; * validation workflow; * revision workflow; * export workflow; * backup/restore expectations; * privacy expectations. --- ## Documentation Plugin documentation belongs inside the plugin: ```text docs/ ``` Recommended documentation set: ```text docs/00_index.md docs/01_architecture_decision.md docs/02_domain_boundaries.md docs/03_moodle_plugin_structure.md docs/04_data_model.md docs/05_media_database_division.md docs/06_file_api_and_storage.md docs/07_permissions_and_roles.md docs/08_archive_workflows.md docs/09_didactic_material_workflows.md docs/10_provenance_versioning_validation.md docs/11_privacy_retention_redaction.md docs/12_backup_restore.md docs/13_services_and_ajax_api.md docs/14_events_and_audit.md docs/15_ui_templates_and_amd.md docs/16_integration_with_courses.md docs/17_integration_with_challenges.md docs/18_integration_with_assemblies.md docs/19_integration_with_integrity.md docs/20_reporting_and_exports.md docs/21_testing_strategy.md docs/22_installation.md docs/23_upgrade.md docs/24_acceptance_checklist.md docs/25_known_gaps_and_corrections.md docs/26_release_notes.md ``` --- ## Installation Place the plugin in: ```text mod/uckkarchive ``` Then visit Moodle site administration to complete plugin installation or upgrade. Development path: ```text C:\mycode\UCKK\moodle\moodle\public\mod\uckkarchive ``` Distribution path: ```text C:\mycode\UCKK\uckk-moodle\mod\uckkarchive ``` --- ## Development rules 1. Keep didactic material separate from grades and administration. 2. Store files through Moodle File API. 3. Store metadata in archive-owned tables. 4. Do not write directly into gradebook tables. 5. Do not let external systems write directly into Moodle source tables. 6. Do not let JavaScript bypass server-side checks. 7. Do not expose restricted records without `mod/uckkarchive:viewrestricted`. 8. Preserve provenance through revisions, exports, backup, restore, and privacy flows. 9. Keep file area names consistent across the whole module. 10. Keep archive authority separate from Assembly, Integrity, Challenge, Report, and Registry authority. --- ## Known alignment gaps The current module is aligned with the accepted architecture, but the following corrections remain important: ### 1. Media layer The module currently treats didactic media as archive items with file attachments. This is acceptable for now. If the media database grows, add explicit tables: ```text uckkarchive_media uckkarchive_media_version uckkarchive_media_relation ``` ### 2. File area normalization Normalize file area names across: ```text add.php lib.php classes/privacy/provider.php backup/moodle2/* restore/moodle2/* tests/* ``` No file area name should appear in one layer but not the others. ### 3. Version dependency check Check `version.php` for accidental self-dependency. `mod_uckkarchive` should not depend on itself. ### 4. Documentation Add the full `docs/` set and keep each file aligned with the accepted division: ```text Archive = didactic material, media, evidence, provenance Gradebook = notes Administration = local_uckk and related tools Assembly = decisions Integrity = cases and procedures Reports = reporting and exports ``` --- ## Status Current status: ```text Architecture alignment: good Archive domain separation: good File API direction: good Privacy provider: present Backup/restore: present Tests: present Dedicated media model: partial Documentation: to complete ``` Decision: ```text Keep this module as the base. Do not restart from zero. Strengthen it with documentation, file-area normalization, and an optional media submodel. ``` ================================================================================================ FILE: README.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 416a91b9cd64058f4a934927ff0fd53c4c2265dfcdbf1075908d6336057296c8 CONTENT_BYTES: 10526 ================================================================================================ ÿþ# UCKK  Univers-Cité King Klown > **Comprendre le jeu. Jouer avec lucidité. Changer les règles.** **UCKK** est l **Univers-Cité King Klown**, un établissement virtuel émergent de puissance opératoire consacré au **Grand Jeu social**. ## UCKK est maintenant en ligne <Øß **[Visiter UCKK.org](https://uckk.org/)** L Univers-Cité est accessible en ligne. UCKK développe un espace d apprentissage consacré à la lecture des systèmes sociaux, de leurs règles, de leurs institutions, de leurs récits, de leurs pouvoirs et de leurs transformations possibles. ## Premier livre lié au projet =ØÚÜ **[Voir le premier livre associé à UCKK sur Amazon](https://a.co/d/0atE1XWE)** Ce livre constitue un premier point d entrée éditorial vers les thèmes, méthodes et questions qui alimentent le développement de l Univers-Cité. --- ## Qu est-ce que l UCKK ? L **Univers-Cité King Klown** est un projet pédagogique et civique émergent lié au mouvement **kOA**. UCKK vise à former des **joueurs lucides du Grand Jeu social** capables de : * comprendre les systèmes sociaux et leurs règles visibles ou invisibles ; * analyser institutions, récits, plateformes, pouvoirs, incitatifs et mémoires ; * enquêter, documenter et distinguer les faits, les hypothèses et les interprétations ; * agir avec méthode, intégrité et responsabilité ; * participer à des défis, projets, assemblées et productions collectives ; * transformer les règles lorsqu elles deviennent injustes, opaques ou destructrices. La formule canonique est : > **L Univers-Cité King Klown est un établissement virtuel de puissance opératoire consacré au Grand Jeu social.** UCKK ne doit pas être présentée comme une université accréditée par l État. Les **Niveaux**, **Parchemins UCKK** et autres reconnaissances décrites dans le corpus sont des reconnaissances internes à l Univers-Cité, sauf reconnaissance officielle future. --- ## À propos de ce dépôt **UCKK_Assets** est le dépôt de documentation et d actifs de l Univers-Cité King Klown. Il rassemble notamment : * le corpus canonique UCKK ; * la nomenclature et les références institutionnelles ; * les cours, guides et parcours pédagogiques ; * les Voies et Niveaux UCKK ; * les documents de communication publique ; * les ressources d identité visuelle ; * les présentations et supports de cours ; * les outils de mise en forme de documents ; * les exports et documents de travail destinés à être réutilisés, révisés ou canonisés. Ce dépôt sert à garder le corpus **clair, versionné, réutilisable, traçable et distinct des dépôts techniques** de l écosystème kOA. ¡'þ **Dépôt public : [Rejean-McCormick/UCKK_Assets](https://github.com/Rejean-McCormick/UCKK_Assets)** --- ## Architecture conceptuelle UCKK conserve une distinction claire entre les principales composantes de l écosystème : ```text kOA = mouvement UCKK = Univers-Cité / institution d apprentissage kOA Digital Ecosystem = infrastructure numérique et sociotechnique King Klown = figure narrative et mobilisatrice Inquisiteur = garde-fou éthique et méthodologique Assemblées = légitimité et délibération collectives Archives = mémoire ``` Une formule résume cette architecture : > **King Klown révèle le jeu.** > **L Inquisiteur garde le jeu honnête.** > **Les Assemblées rendent le jeu collectif.** > **Les Joueurs apprennent à mieux jouer.** > **Les Bâtisseurs changent les règles.** > **L Archiviste garde la mémoire.** > **L Univers-Cité relie le tout.** --- ## Structure du dépôt ```text UCKK_Assets/ %%% UCKK_Canon_v4/ # Documents canoniques et nomenclature UCKK %%% Cours/ # Cours, guides, manuels et matériel pédagogique %%% Branding_visuel/ # Identité visuelle et matériel de communication %%% Auto_Format/ # Outils de standardisation et de mise en forme %%% Atlas conceptuel.../ # Références vers l atlas conceptuel des Voies ``` Les documents du dossier `UCKK_Canon_v4/` constituent la principale référence pour la terminologie, l architecture institutionnelle, les Voies, les Niveaux et les limites de présentation publique de l UCKK. --- ## Principes de travail Les documents UCKK cherchent à préserver : * la clarté conceptuelle ; * la traçabilité des versions et des sources ; * la distinction entre fait, hypothèse, interprétation, fiction et décision ; * l auditabilité des méthodes et des productions ; * la dignité des personnes ; * le droit de contestation et de correction ; * une séparation nette entre le corpus public/pédagogique et l infrastructure technique privée. --- ## Liens * **UCKK en ligne :** https://uckk.org/ * **Premier livre lié au projet :** https://a.co/d/0atE1XWE * **UCKK Assets :** https://github.com/Rejean-McCormick/UCKK_Assets --- ## Statut UCKK est un projet émergent. Son corpus, ses parcours et ses outils évoluent par versions successives. Les documents canoniques du dépôt servent de référence de travail pour maintenir cette évolution cohérente, explicite et révisable. ================================================================================================ FILE: release/acceptance-checklist.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: d5c06a749c93b75d26f5a4132597d7072106f354164ca6d5cd088147909dba03 CONTENT_BYTES: 21513 ================================================================================================ # Release Acceptance Checklist **Status:** Release gate checklist for UCKK-Moodle final code revision **Applies to:** UCKK-Moodle code snapshot and release package **Primary mode:** `standalone_core` **Optional mode:** `connected_konnaxion` This file is the executable release checklist for the code-revision phase. It separates: ```text standalone_core = required for final core release connected_konnaxion = optional connected-mode profile; required only when claimed as supported ``` A release may pass `standalone_core` while `connected_konnaxion` is marked `not_included`, provided no UI, docs, seed preset, release note, or manifest claims that Konnaxion/Smart Vote is operational. ## 0. Release decision summary Fill this block before release sign-off. ```text Release version: Snapshot/source revision: Moodle target version: PHP target version: Database target: Reviewer: Review date: Core standalone status: pass / fail Connected Konnaxion status: not_included / included_pass / included_fail Final release decision: pass / fail ``` ## 1. Governing release rules ```text UCKK-Moodle is self-standing. Konnaxion is optional connected-mode integration. Smart Vote is a reading, not an automatic decision. Moodle capabilities remain authoritative. External systems never write directly into Moodle source tables. AI outputs are assistive only. ``` Required registry alignment: ```text DOC_00 = docs/00_master_execution_doctrine.md DOC_11 = docs/11_cross_doc_alignment_registry.md OPERATING_MODE_STANDALONE = standalone_core OPERATING_MODE_KONNAXION_CONNECTED = connected_konnaxion KONNAXION_REQUIRED_FOR_CORE = false SMART_VOTE_REQUIRED_FOR_CORE = false ``` ## 2. Release package completeness The release package must contain: ```text plugins/ presets/ docs/ tests/ release/installation.md release/upgrade.md release/rollback.md release/acceptance-checklist.md CHANGELOG.md LICENSE.md README.md ``` Checklist: ```text [ ] release/acceptance-checklist.md exists. [ ] release/installation.md exists or is explicitly deferred. [ ] release/upgrade.md exists or is explicitly deferred. [ ] release/rollback.md exists or is explicitly deferred. [ ] README.md is UTF-8 Markdown and not null-byte/UTF-16 corrupted. [ ] CHANGELOG.md exists or is explicitly deferred. [ ] LICENSE.md exists or is explicitly deferred. [ ] docs/11_cross_doc_alignment_registry.md exists and is current. [ ] docs/12_current_code_snapshot_gap_report.md exists before final sign-off. ``` ## 3. Static filetype blockers These checks are required for `standalone_core`. ### 3.1 PHP files ```bash find . -name '*.php' -not -path './vendor/*' -print0 | xargs -0 -n1 php -l ``` Pass criteria: ```text [ ] Every PHP file parses successfully. [ ] Every PHP source file starts with /dev/null find . -name 'install.xml' -print0 | xargs -0 -n1 xmllint --noout grep -RIn --include='*.css' --include='*.scss' ' theme_uckk course/format/uckk => format_uckk local/uckk => local_uckk blocks/uckk_dashboard => block_uckk_dashboard mod/uckkchallenge => mod_uckkchallenge mod/uckkassembly => mod_uckkassembly mod/uckkarchive => mod_uckkarchive admin/tool/uckkseed => tool_uckkseed admin/tool/uckkintegrity => tool_uckkintegrity report/uckk => report_uckk ai/provider/uckk => aiprovider_uckk ``` Checklist: ```text [ ] Every version.php has the correct $plugin->component. [ ] Every @package tag matches the component or is corrected. [ ] Every language file component name matches the plugin. [ ] Every capability prefix matches the plugin component. [ ] Every service component matches the plugin component. [ ] Every event namespace matches the plugin component. [ ] Every AMD module name matches the plugin component. [ ] Every template name matches the plugin component. [ ] Every privacy provider namespace matches the plugin component. ``` Known current-snapshot blocker to clear: ```text [ ] mod/uckkarchive/version.php declares $plugin->component = 'mod_uckkarchive'. ``` ## 5. Declared class existence The release fails if a page, service, event, task, form, output renderer, local class, or test references a class that does not exist. Required checks: ```text [ ] Every db/services.php classname maps to an existing classes/external/*.php class. [ ] Every db/tasks.php classname maps to an existing classes/task/*.php class. [ ] Every db/events.php observer maps to an existing callback/class where applicable. [ ] Every triggered event class exists under classes/event/. [ ] Every referenced form class exists under classes/form/ or a valid legacy form path. [ ] Every referenced output class exists under classes/output/. [ ] Every referenced local/service/api class exists under classes/local/, classes/service/, or classes/api/. ``` Current-snapshot class-creation groups to resolve: ```text [ ] mod/uckkarchive referenced event/external/form/local/output classes exist. [ ] mod/uckkassembly referenced completion/event/external/local/output classes exist. [ ] mod/uckkchallenge referenced event/external/local/output/task classes exist. [ ] local_uckk referenced api/event/external/local/service/task classes exist. [ ] tool_uckkseed referenced form/local/output classes exist. [ ] tool_uckkintegrity referenced external/form/local/output classes exist. [ ] block_uckk_dashboard referenced output classes exist. [ ] format_uckk referenced local classes exist. [ ] report_uckk referenced local/output classes exist. [ ] aiprovider_uckk referenced provider/local classes exist. ``` ## 6. Privacy provider gate Every plugin that stores, displays, exports, logs, derives, or aggregates personal data must include a privacy provider. Checklist: ```text [ ] theme/uckk/classes/privacy/provider.php exists or is explicitly metadata-only with null provider. [ ] course/format/uckk/classes/privacy/provider.php exists. [ ] local/uckk/classes/privacy/provider.php exists. [ ] blocks/uckk_dashboard/classes/privacy/provider.php exists. [ ] mod/uckkchallenge/classes/privacy/provider.php exists. [ ] mod/uckkassembly/classes/privacy/provider.php exists. [ ] mod/uckkarchive/classes/privacy/provider.php exists. [ ] admin/tool/uckkseed/classes/privacy/provider.php exists. [ ] admin/tool/uckkintegrity/classes/privacy/provider.php exists. [ ] report/uckk/classes/privacy/provider.php exists. [ ] ai/provider/uckk/classes/privacy/provider.php exists. ``` Provider behavior checklist: ```text [ ] Metadata declaration is implemented. [ ] User data export is implemented or explicitly empty where no personal data is stored. [ ] Delete/anonymise behavior is implemented or explicitly empty where no personal data is stored. [ ] Retention/redaction behavior is documented where records are institutional. [ ] Archive-retention exceptions are documented where applicable. [ ] PHPUnit privacy provider tests exist or are explicitly deferred with reason. ``` ## 7. Database and upgrade gate Checklist: ```text [ ] Every db/install.xml validates. [ ] Every table name matches DOC_04 and DOC_11. [ ] Every primary key/index is valid for Moodle XMLDB. [ ] Every db/upgrade.php parses and is idempotent. [ ] Upgrade does not duplicate tables, roles, capabilities, scheduled tasks, seed records, admin settings, or event registry rows. [ ] Backup/restore code exists for activity modules where required. [ ] Activity restore code is in PHP class files, not templates. ``` ## 8. Capability and access-control gate Standalone-core capabilities must match the current code and DOC_11. Checklist: ```text [ ] local/uckk capabilities match local/uckk/db/access.php and DOC_11. [ ] mod/uckkassembly capabilities match mod/uckkassembly/db/access.php and DOC_11. [ ] mod/uckkarchive capabilities match mod/uckkarchive/db/access.php and DOC_11. [ ] mod/uckkchallenge capabilities match mod/uckkchallenge/db/access.php and DOC_11. [ ] tool_uckkseed capabilities match admin/tool/uckkseed/db/access.php and DOC_11. [ ] tool_uckkintegrity capabilities match admin/tool/uckkintegrity/db/access.php and DOC_11. [ ] report_uckk capabilities match report/uckk/db/access.php and DOC_11. [ ] aiprovider_uckk capabilities match ai/provider/uckk/db/access.php and DOC_11. [ ] Deprecated aliases are absent from active code and presets. [ ] Every page resolves context before checking capability. [ ] Every write operation requires sesskey or valid external-service token. [ ] No role label, symbolic title, external identifier, or Konnaxion value grants Moodle authority. ``` Deprecated aliases must appear only in DOC_11 or explicit migration notes. ## 9. Seed and preset gate Standalone-core seed must not require Konnaxion. Checklist: ```text [ ] Core seed dry-run works without Konnaxion credentials. [ ] Core seed apply works without Konnaxion credentials. [ ] Core seed verify works without Konnaxion credentials. [ ] Core seed rollback_plan works without Konnaxion credentials. [ ] Core presets are valid JSON. [ ] Runtime preset paths under admin/tool/uckkseed/presets/ are correct. [ ] Repository mirror preset paths under uckk-presets/ are either synced or explicitly non-runtime mirrors. [ ] Seed logs do not store secrets. [ ] Seed idempotency prevents duplicates. [ ] Konnaxion mapping presets are not required for standalone-core. ``` ## 10. Standalone-core functional gate These must pass without Konnaxion enabled. ```text [ ] Moodle detects all plugins with correct component names. [ ] Moodle upgrade completes without fatal error. [ ] Moodle caches can be purged. [ ] theme_uckk applies successfully. [ ] format_uckk course loads. [ ] local_uckk settings and pages load. [ ] block_uckk_dashboard displays for authorized users. [ ] mod_uckkchallenge can be created and viewed. [ ] mod_uckkassembly can be created and viewed. [ ] mod_uckkarchive can be created and viewed. [ ] tool_uckkseed page loads. [ ] tool_uckkintegrity index loads. [ ] report_uckk index loads. [ ] aiprovider_uckk settings page loads. [ ] Joueur dashboard works. [ ] Challenge proof submission workflow works or is explicitly deferred. [ ] Challenge evaluation workflow works or is explicitly deferred. [ ] Assembly motion workflow works or is explicitly deferred. [ ] Assembly ordinary vote/readings workflow works or is explicitly deferred. [ ] Assembly decision publication workflow works or is explicitly deferred. [ ] Archive item/proof/provenance workflow works or is explicitly deferred. [ ] Integrity case workflow works or is explicitly deferred. [ ] Reports are visible only to authorized users. ``` ## 11. AMD build gate ```bash npx grunt amd ``` Checklist: ```text [ ] AMD source files build. [ ] Generated build files are produced where expected. [ ] No AMD source contains PHP controller code. [ ] No JavaScript failure breaks core page workflows. [ ] JavaScript calls only declared external services. [ ] Server-side permission checks remain authoritative. ``` ## 12. PHPUnit gate Recommended command pattern: ```bash php admin/tool/phpunit/cli/init.php vendor/bin/phpunit local/uckk/tests vendor/bin/phpunit mod/uckkarchive/tests vendor/bin/phpunit mod/uckkassembly/tests vendor/bin/phpunit mod/uckkchallenge/tests vendor/bin/phpunit admin/tool/uckkseed/tests vendor/bin/phpunit admin/tool/uckkintegrity/tests vendor/bin/phpunit blocks/uckk_dashboard/tests vendor/bin/phpunit course/format/uckk/tests vendor/bin/phpunit report/uckk/tests vendor/bin/phpunit ai/provider/uckk/tests ``` Standalone-core pass criteria: ```text [ ] PHPUnit initializes. [ ] Core tests pass for installed components. [ ] Privacy provider tests pass or are explicitly deferred with reason. [ ] Access-control allow/deny tests pass. [ ] External service parameter validation tests pass. [ ] Seed idempotency tests pass. [ ] Archive/integrity/report tests pass or are explicitly deferred with reason. [ ] No test requires Konnaxion credentials for standalone-core. ``` ## 13. Behat gate Recommended command pattern: ```bash php admin/tool/behat/cli/init.php php admin/tool/behat/cli/run.php --tags='@uckk' ``` Standalone-core pass criteria: ```text [ ] Behat initializes. [ ] Install/seed campus flow passes or is explicitly deferred. [ ] Joueur dashboard scenario passes or is explicitly deferred. [ ] Challenge scenario passes or is explicitly deferred. [ ] Assembly ordinary decision scenario passes or is explicitly deferred. [ ] Archive scenario passes or is explicitly deferred. [ ] Integrity scenario passes or is explicitly deferred. [ ] Report visibility scenario passes or is explicitly deferred. [ ] AI non-authority warning scenario passes or is explicitly deferred. [ ] No scenario requires Konnaxion credentials for standalone-core. ``` ## 14. Backup/restore gate Required for activity modules: ```text [ ] mod_uckkchallenge backup and restore are valid or explicitly deferred. [ ] mod_uckkassembly backup and restore are valid or explicitly deferred. [ ] mod_uckkarchive backup and restore are valid. [ ] Backup code is PHP only. [ ] Restore code is PHP only. [ ] No backup/restore PHP appears in Mustache templates. [ ] Restored records preserve ownership, provenance, visibility, and privacy constraints. ``` ## 15. Documentation alignment gate Checklist: ```text [ ] docs/11_cross_doc_alignment_registry.md is current. [ ] docs/12_current_code_snapshot_gap_report.md lists all known blockers. [ ] docs do not claim connected_konnaxion is implemented unless it is included and tested. [ ] docs do not require Konnaxion for standalone-core. [ ] DOC_10 path is docs/10_konnaxion_smart_vote_integration_contract.md. [ ] OPTIONAL_KONNAXION_CONTRACT is not used as an active variable. [ ] Deprecated capability aliases appear only in DOC_11 or migration notes. [ ] Static grep gates distinguish executable PHP-in-JS from harmless deprecated-alias registry entries. [ ] Release notes state whether connected_konnaxion is included, not included, or deferred. ``` ## 16. Connected Konnaxion / Smart Vote gate This section is required only when `connected_konnaxion` is included or claimed as supported. If not included, mark: ```text connected_konnaxion = not_included ``` and complete only the deferral checks below. ### 16.1 Deferral checks when not included ```text [ ] No UI claims Konnaxion is operational. [ ] No UI claims Smart Vote is operational. [ ] No release manifest claims connected_konnaxion support. [ ] Missing Konnaxion tables are documented as target_connected_mode, not core blockers. [ ] Missing Smart Vote tables are documented as target_connected_mode, not core blockers. [ ] Missing Konnaxion services/events/classes are documented as target_connected_mode, not core blockers. [ ] Missing Smart Vote services/events/classes are documented as target_connected_mode, not core blockers. ``` ### 16.2 Required checks when included ```text [ ] Konnaxion bridge settings exist and are disabled by default. [ ] Konnaxion API credentials use secure Moodle config handling. [ ] Konnaxion health check works without exposing secrets. [ ] Konnaxion health check fails safely when unconfigured. [ ] Konnaxion user/object mapping tables exist with canonical names. [ ] Konnaxion sync log table exists with canonical name. [ ] Smart Vote target/snapshot/audit tables exist with canonical names. [ ] Konnaxion services exist and match DOC_11. [ ] Smart Vote services exist and match DOC_11. [ ] Konnaxion events exist and match DOC_11. [ ] Smart Vote events exist and match DOC_11. [ ] Smart Vote request/import/review/contest/archive/report flows are capability-checked. [ ] Smart Vote result appears as reading, not final decision. [ ] Smart Vote snapshots preserve raw data reference, method, computed reading, provenance, visibility, and contestation status. [ ] Konnaxion outage fails safely. [ ] Konnaxion timeout, retry, failure, disabled-state, and idempotency behavior is tested. [ ] Konnaxion/Smart Vote privacy export/delete/redaction is tested. [ ] Connected-mode PHPUnit tests pass. [ ] Connected-mode Behat tests pass. ``` ## 17. Security and privacy sign-off ```text [ ] No secrets appear in logs, reports, archives, events, AI prompts, AI responses, Behat output, or PHPUnit failure dumps. [ ] No write operation is possible by GET alone. [ ] All external services validate parameters and returns. [ ] All file-serving paths check context, capability, visibility, and privacy. [ ] Restricted integrity/archive data is never exposed to ordinary users. [ ] AI outputs are labelled non-authoritative. [ ] AI prompt/response logs are disabled by default or privacy-covered. [ ] Data export/delete behavior is documented and tested. ``` ## 18. Final sign-off table | Gate | Required for standalone_core | Status | Notes | |---|---:|---|---| | Release package completeness | yes | pass / fail | | | Static filetype blockers | yes | pass / fail | | | Moodle component identity | yes | pass / fail | | | Declared class existence | yes | pass / fail | | | Privacy providers | yes | pass / fail | | | Database/upgrade | yes | pass / fail | | | Capability/access-control | yes | pass / fail | | | Seed/presets | yes | pass / fail | | | Standalone functional checks | yes | pass / fail | | | AMD build | yes | pass / fail | | | PHPUnit | yes | pass / fail | | | Behat | yes | pass / fail | | | Backup/restore | yes, for activity modules | pass / fail | | | Documentation alignment | yes | pass / fail | | | Connected Konnaxion/Smart Vote | only if claimed | not_included / pass / fail | | | Security/privacy sign-off | yes | pass / fail | | Final decision: ```text [ ] PASS — standalone_core release is accepted. [ ] PASS — connected_konnaxion profile is accepted. [ ] PASS — connected_konnaxion is not included and is explicitly deferred. [ ] FAIL — release is rejected pending listed fixes. ``` Reviewer notes: ```text ``` ================================================================================================ FILE: UCKK_Ops_Console_Runbook.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 6d7c60aa7c28558b5c5197abbee2c1c069f9ceebe0e94f16bfd39c1442814103 CONTENT_BYTES: 3232 ================================================================================================ # UCKK Ops Console — Runbook ## Objet UCKK Ops Console pilote les opérations courantes entre le repo source local `uckk-moodle`, le runtime Moodle local, Git, le serveur `uckk.org` et les seeds Moodle. ```text source locale → runtime local → Git → serveur source → serveur runtime → DB/cache Moodle ``` ## Fichiers de l’app ```text tools/uckk-ops/uckk_ops_gui.ps1 tools/uckk-ops/uckk-ops.config.json tools/uckk-ops/lib/UckkOps.Common.psm1 tools/uckk-ops/lib/UckkOps.Local.psm1 tools/uckk-ops/lib/UckkOps.Git.psm1 tools/uckk-ops/lib/UckkOps.Server.psm1 tools/uckk-ops/lib/UckkOps.Seed.psm1 tools/uckk-ops/lib/UckkOps.Smoke.psm1 tools/uckk-ops/UCKK_Ops_Console_RUN.bat docs/UCKK_Ops_Console_Runbook.md ``` ## Source de configuration Toutes les variables viennent de : ```text tools/uckk-ops/uckk-ops.config.json ``` Aucun chemin ne doit être défini directement dans les modules `.psm1`. ## Chemins locaux ```text Source Git locale: C:\mycode\UCKK\uckk-moodle Runtime Moodle local: C:\mycode\UCKK\moodle\moodle\public URL locale: http://localhost:8000 ``` ## Chemins serveur ```text SSH: ubuntu@57.129.115.159 Source serveur: /opt/uckk/uckk-moodle Runtime Moodle serveur: /var/www/moodle/public Moodle root: /var/www/moodle Moodle data: /var/moodledata URL publique: https://uckk.org ``` ## Workflow normal ### 1. Développement local ```text Check paths Sync source → Moodle local Purge caches local Start Moodle local ``` Tester ensuite dans le navigateur. ### 2. Git ```text Git status Git diff Commit + push ``` Ne pas pousser si le diff contient des secrets, `config.php`, dumps SQL, clés privées ou fichiers personnels. ### 3. Déploiement serveur ```text Test SSH Pull server repo Sync server source → runtime Moodle upgrade Purge server caches Reload php-fpm Smoke test ``` Ne jamais faire de sync serveur sans vérifier le dernier commit. ### 4. Seeds Moodle Pour `academic_registry_json/categories.json` : ```text Dry-run categories Apply categories Purge caches Smoke test course index ``` Modifier le JSON ne suffit pas : l’affichage Moodle des catégories vient de la DB Moodle. ## Actions sensibles Les actions suivantes doivent demander confirmation : ```text Commit + push Sync server source → runtime Moodle upgrade Apply categories Apply courses Apply programs Apply pathways ``` Message recommandé : ```text Cette action modifie uckk.org ou sa base Moodle. Continuer ? ``` ## Smoke tests recommandés Local : ```text http://localhost:8000 http://localhost:8000/course/index.php http://localhost:8000/local/uckk/programs.php ``` Serveur : ```text https://uckk.org https://uckk.org/course/index.php https://uckk.org/local/uckk/programs.php ``` ## Règle de sécurité Ne jamais stocker dans le repo : ```text mots de passe clés SSH privées tokens config.php serveur dumps SQL secrets Moodle secrets DB ``` ## Rollback minimal ```text 1. Revenir au commit précédent dans /opt/uckk/uckk-moodle 2. Resynchroniser source serveur → runtime 3. Relancer upgrade Moodle si nécessaire 4. Purger les caches 5. Tester uckk.org ``` Commande indicative : ```bash cd /opt/uckk/uckk-moodle git log --oneline -5 git checkout ```