# INITKOA CONTEXT PACK repository: Rejean-McCormick/Orgo source_commit: fba068aa8008771b72e41b39370564c5287d0a91 source_mode: git working_tree_markdown: clean working_tree_selected: clean selection_mode: markdown wiki_source_commit: 05d4ed6e021761e7b8762563b571fb1ac989f7b5 wiki_working_tree_markdown: clean policy_version: 2026-09-10.13 repo_files: 48 wiki_files: 20 source_files: 68 included_files: 63 excluded_files: 5 duplicate_files: 0 content_bytes: 499503 authority_counts: {"reference":63} content_role_counts: {"knowledge":43,"navigation":20} generated_at: 2026-09-10T13:04:14-04:00 files: 63 content_sha256: 6ae71f9e373f132de26800d7bbacdffdecd1d716e2af9c61265ab25458f201d8 ================================================================================================ FILE INDEX ================================================================================================ 01. [reference] [navigation] wiki/_Footer.md | bytes=132 | sha256=e90fbdf30d0e41a7fd73ed879c7f504908e83a991cdaceda4f9b4d0659dbd610 02. [reference] [navigation] wiki/_Sidebar.md | bytes=816 | sha256=af5033920ebe92dcefa584fd2b83c3200a3eddd7b862b4b35b57550be01f13e1 03. [reference] [navigation] wiki/Cases-and-Tasks.md | bytes=1821 | sha256=d4bab76310f1a56b64a2979bb94121942a6365baf054664417d70bc0b1b28ea3 04. [reference] [navigation] wiki/Cyclic-Overview-and-Insights.md | bytes=1346 | sha256=0b555879e54a05716cdc58617a5e13fb9e06b70c7822c3e3968953de78340eb6 05. [reference] [navigation] wiki/Domains-and-Use-Cases.md | bytes=1834 | sha256=af81b62c49840b7466ce2efe9655741e9bf6ae0a4e3eb5fa805cca5e93488c90 06. [reference] [navigation] wiki/Example-Scenarios.md | bytes=1998 | sha256=e1a3361e5ebaafed535afb3fd5c6b4a148f3b47717956740856e0dd2f984577e 07. [reference] [navigation] wiki/FAQ.md | bytes=2701 | sha256=8a1d7816d54998c0bb8287131f71fd38907be402379e8b442da1dfe4af811f71 08. [reference] [navigation] wiki/Glossary.md | bytes=1884 | sha256=766ecc95f91823a74f78b8f8e322a4e2c31ee21e50e7dbbcc44bd8024e617b8d 09. [reference] [navigation] wiki/Home.md | bytes=3078 | sha256=0679834eec057ebe24d8024ba81fea233fdd4bc891b991df7908b24c1b49b4a3 10. [reference] [navigation] wiki/How-Orgo-Works.md | bytes=1997 | sha256=c62d68c72889bf38b8c99331c54dca60cb3e16c17e34186c3b208f9451dfae5f 11. [reference] [navigation] wiki/Interoperability.md | bytes=1828 | sha256=38e0b4b34248d60c19f9d0039c08808210a0964f0823a758bacfbf0ba6912c8e 12. [reference] [navigation] wiki/Offline-and-Resilience.md | bytes=1115 | sha256=075d547307f7a76b9d5bc07a486dc750189b94509982e4b971f6f619a4934b84 13. [reference] [navigation] wiki/Organizations-People-and-Privacy.md | bytes=1439 | sha256=23abd2ffe4dee17c9eab8be7989b8f9063e3951bfaadcdb35e3dd40ec30b5c96 14. [reference] [navigation] wiki/Profiles-and-Adaptability.md | bytes=1147 | sha256=5d0b2f9a3d9c05cfd0d18a2e2ddc019b83a724864166420af5dde7fbd2b000b3 15. [reference] [navigation] wiki/Reactivity-and-Escalation.md | bytes=1595 | sha256=30c2f0f75cedd3b2092b7f7ad1edd1412fb6e2051a33c240ec79f1aa6ca54ffd 16. [reference] [navigation] wiki/Resources.md | bytes=423 | sha256=320daacdd6541ed07914f29644ecaa09a062d3feceeb7cdde2cbe45209ab5a22 17. [reference] [navigation] wiki/Routing-and-Labels.md | bytes=1299 | sha256=2431441d5a285f0d5a0e27c122c512db75275e27c35eee4612acb51a9f594f8e 18. [reference] [navigation] wiki/Semantic-Charters.md | bytes=1719 | sha256=6f0cafe14b8e2210388e9263ed20c36b6d5ee66a356ac9f8c18e487bc76e8189 19. [reference] [navigation] wiki/Signals-and-Workflows.md | bytes=1550 | sha256=b8bfd927e0c739bd796ea032ec059143c50714993a0a641aa6f4bec5bc7e0ca4 20. [reference] [navigation] wiki/What-is-Orgo.md | bytes=2201 | sha256=1398dcfbe5504f72984d6c9364ec0cf83bccc96838f120ec5062a732214dc3f6 21. [reference] [knowledge] apps/api/README.md | bytes=206 | sha256=edd1819af6b8f652719c0a4f0b71905fe35b80e9bfd24ae5f9433b916b400c50 22. [reference] [knowledge] apps/web/README.md | bytes=289 | sha256=e47c0bb330e89cd9c0e4a244509de0ac6967c7d20be5f54692738e2856fa3933 23. [reference] [knowledge] CODE_SNAPSHOT_MANIFEST.md | bytes=15646 | sha256=3adeddce2bb6fc26e6bb2013744bed7c12bb464ac4c50f953d1cde7a7a28a728 24. [reference] [knowledge] Docs/README.md | bytes=4316 | sha256=cde22c1b878242baf6d6111bc50491319a6d90e1dc3101d6b330c5c4e7f48208 25. [reference] [knowledge] Docs/status/2026-09-10-beta-status.md | bytes=4381 | sha256=5b6cf02af37f3ead67ae17b025754834afe977721c6c97ed884dca3f687044a5 26. [reference] [knowledge] Docs/Technical-Reference/API_IMPLEMENTED.md | bytes=8057 | sha256=d210e31589cc6f69f31c1b396322c6ec8cf33885c4f4aa53a8a58bc593169121 27. [reference] [knowledge] Docs/Technical-Reference/ARCHITECTURE_TO_CODE.md | bytes=4304 | sha256=0c1a272d26262c0ccab0b8eaadc34347c0ec7bb48db9aecc0a39bd54b408f67a 28. [reference] [knowledge] Docs/Technical-Reference/Boilerplate_Turborepo.md | bytes=2263 | sha256=adbb8be266bc9663242de812e2cd4f878f9d5011c3b52c5bd8c760d2fa026899 29. [reference] [knowledge] Docs/Technical-Reference/BOUNDARIES_AND_OWNERSHIP.md | bytes=5598 | sha256=c4205b4cd0f877ee5e731532564340460e2dbc62ca46e63a433176dcef348a0e 30. [reference] [knowledge] Docs/Technical-Reference/CODE_ALIGNMENT_NOTES.md | bytes=19550 | sha256=19e1f2ab22b3857288043d92d0496c169eb673f4c1f5031d04ca324e4040071e 31. [reference] [knowledge] Docs/Technical-Reference/COMPLETION_DECISIONS.md | bytes=9200 | sha256=4ef41a73829d18a5c7b99ccfbe74bb1e8b693b7843d1533d566fa492143030e6 32. [reference] [knowledge] Docs/Technical-Reference/CONTRACTS.md | bytes=7155 | sha256=41d8aa0a6d96ad8a3cd973c8cec981b28ac062622c9898e1dad5fdb938edcebe 33. [reference] [knowledge] Docs/Technical-Reference/GLOSSARY.md | bytes=5487 | sha256=5c8356720877b3bb21330e7d6811f80782c54a2064f811bd596250d1083dce25 34. [reference] [knowledge] Docs/Technical-Reference/IMPLEMENTATION_DECISIONS.md | bytes=9038 | sha256=0fe33a3a2e70e8fc5bb05ad3745bf025e7ee39e2304785455eb20de796e220f3 35. [reference] [knowledge] Docs/Technical-Reference/IMPLEMENTATION_STATUS.md | bytes=6763 | sha256=ce086cef2e1c743c027689741cf9b661bd13923c4f39127ecc392764838cba1c 36. [reference] [knowledge] Docs/Technical-Reference/INTEGRATION_BRIDGE.md | bytes=4218 | sha256=0da629b20f824ea1745da1cf040cd397e8863e3449827fa8174ce887a6365762 37. [reference] [knowledge] Docs/Technical-Reference/LOCAL_VALIDATION.md | bytes=5403 | sha256=2773d9d3298d4fc43b442cdf88d5b806ee8bca0fd7fbabcce2f8d53118e7acbc 38. [reference] [knowledge] Docs/Technical-Reference/Semantic-Charters.md | bytes=7137 | sha256=ecb6cd50387aadf9821ba0a9faa2b111257038c0393a6a70814081f36c0ee7ca 39. [reference] [knowledge] Docs/Technical-Reference/TARGET_ARCHITECTURE.md | bytes=17758 | sha256=ddb637b0e2b09ee3be3b9ba961bbaf1e5a47ad4192d49221f4d6ae68e9b2f453 40. [reference] [knowledge] Docs/Technical-Reference/UI_AND_KOALI_INTEGRATION.md | bytes=11959 | sha256=dc142c599a095d89cd95f60640634fc9f855d5cd47b5293c6b0fd6971a0186ca 41. [reference] [knowledge] Docs/Technical-Reference/v3/1-Orgo v3 - Database Schema Reference.md | bytes=5611 | sha256=216f9cc8d5b655953ccff79c7a6e6a3b38d76b8b1399ae4e4e738144f4480c2e 42. [reference] [knowledge] Docs/Technical-Reference/v3/1-orgo-database-schema-reference.md | bytes=47606 | sha256=1d5d33ee1859e5dbb0ab4349c8118de6358c23a8575400c3495382c382b29cbb 43. [reference] [knowledge] Docs/Technical-Reference/v3/2-Orgo v3 - Architecture and Invariants.md | bytes=8752 | sha256=32fb353b996b3127d47b1c506182aef0d9b7ea36179d2bbb880db4997570d0f8 44. [reference] [knowledge] Docs/Technical-Reference/v3/2-orgo-documentation-index.md | bytes=31141 | sha256=4f9b300feae5109e99738b92e7eea956ab7f3af220f77ad0c3a7cce1c5b8d79b 45. [reference] [knowledge] Docs/Technical-Reference/v3/3-Orgo v3 - Task Case and Workflow Contract.md | bytes=6078 | sha256=58731c133f3be8823076978de7ec658c33ad8d3fd63a45f200511aeaae775cf2 46. [reference] [knowledge] Docs/Technical-Reference/v3/3-orgo-full-stack-technical-spec.md | bytes=28392 | sha256=153f921c269a3b6e2dd83fbbfcd2380f765edd3d23bfa9f2104f275b6732723d 47. [reference] [knowledge] Docs/Technical-Reference/v3/4-Orgo v3 - Domain Modules.md | bytes=3091 | sha256=3218eca4e4b8dddca16a36b73ee7efdad46f77865605e396deb9f04381785daf 48. [reference] [knowledge] Docs/Technical-Reference/v3/4-orgo-functional-code-name-inventory.md | bytes=46326 | sha256=162a126d2383a66547e8bcde7bccdd1db3ed56c27d98d8670a04b1d354a3d04e 49. [reference] [knowledge] Docs/Technical-Reference/v3/5-Orgo v3 - Labels Profiles and Cyclic Overview.md | bytes=1931 | sha256=17f1b6c211135258ad1eb5b6d128e52855a45542b9bafa0221a492d9273a9281 50. [reference] [knowledge] Docs/Technical-Reference/v3/5-orgo-Core-Services-Specification.md | bytes=40973 | sha256=1f78e6f73f4c1aa21715d2f3b74c81c0fbfa5de1656649f53728c6b6d2e7d02d 51. [reference] [knowledge] Docs/Technical-Reference/v3/6-Orgo v3 - Insights and Analytics.md | bytes=1969 | sha256=629c53ebcab194b0a908102faa7abb93c0a3bf0e91d9d2bc7475bb1f1715af37 52. [reference] [knowledge] Docs/Technical-Reference/v3/6-orgo-insights-module-config-parameters.md | bytes=29951 | sha256=7183935cc369671486769060758e2baa7ff46b591147659bcfa89f0dc5250d3e 53. [reference] [knowledge] Docs/Technical-Reference/v3/7-Orgo v3 - API Surface.md | bytes=3706 | sha256=85155be5e53283eb4c1bc983ad0c01a85cffc561d68032cbc5a8694b33f73d7b 54. [reference] [knowledge] Docs/Technical-Reference/v3/7-orgo-organization-profiles-and-cyclic-overview.md | bytes=21619 | sha256=01ec9e77a8968bcd78a8fab691ce6f42ca3fd9e0d5d2fba5fd8acd138fdfa4e5 55. [reference] [knowledge] Docs/Technical-Reference/v3/8-Orgo v3 - Documentation Index.md | bytes=1543 | sha256=5bc04cd7a75ca6980a603a7f44b857c474de2f5c82213c058d9546c5e0e976c7 56. [reference] [knowledge] Docs/Technical-Reference/v3/8-orgo-cyclic-overview-labels-and-flow-rules.md | bytes=29606 | sha256=f144c92bf18d6fc23f730bd829d35ebbbf5fa54ce5878967ba4649fea2c61282 57. [reference] [knowledge] Docs/Technical-Reference/WikiData-Orgo_Chart.md | bytes=6733 | sha256=61469f1577eb077a6a5ac0318980c39075d7e9bc65df07524185931cf653dd77 58. [reference] [knowledge] legacy/README.md | bytes=252 | sha256=95c071ccbff8226ae71f49e8406dc307247e46eabd54619974767616a8dfdc44 59. [reference] [knowledge] packages/README.md | bytes=229 | sha256=3194cfb55b18cd7fc9bec28fe853673f13e24090ce37e6eba1505be95d5767cb 60. [reference] [knowledge] packages/tsconfig/README.md | bytes=106 | sha256=d39b75548339193750b127f369063e86a96897a6e5753bd3a73a233f2ac4f1f7 61. [reference] [knowledge] README.md | bytes=2503 | sha256=a60f3bf4ad60e9aab52da73b6b684a886be5a6d398aaf6381c8e6a77acff3810 62. [reference] [knowledge] validation/completion/STATUS.md | bytes=438 | sha256=f6c47d66c878ada27597ec5d566515a525c11e0ff281b50d93293687a463bcf3 63. [reference] [knowledge] validation/README.md | bytes=296 | sha256=bbb8609f65d9da277774b5461f9b7abff436cdd80898360c74c0cc0a6ce385d3 ================================================================================================ EXCLUDED FILES ================================================================================================ - [proposal] Docs/Technical-Reference/Architecture upgrade(to do)/OPS-001_AI_Resilience_Strategy.md (repo:Docs/Technical-Reference/Architecture upgrade(to do)/**) - [proposal] Docs/Technical-Reference/Architecture upgrade(to do)/REF-001_Configuration_Manifest.md (repo:Docs/Technical-Reference/Architecture upgrade(to do)/**) - [proposal] Docs/Technical-Reference/Architecture upgrade(to do)/RFC-001_Nervous_System_Upgrade.md (repo:Docs/Technical-Reference/Architecture upgrade(to do)/**) - [proposal] Docs/Technical-Reference/Architecture upgrade(to do)/SPEC-001_Input_SenTient_ACL.md (repo:Docs/Technical-Reference/Architecture upgrade(to do)/**) - [proposal] Docs/Technical-Reference/Architecture upgrade(to do)/SPEC-002_Output_Architect_Outbox.md (repo:Docs/Technical-Reference/Architecture upgrade(to do)/**) ================================================================================================ FILE: wiki/_Footer.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: e90fbdf30d0e41a7fd73ed879c7f504908e83a991cdaceda4f9b4d0659dbd610 CONTENT_BYTES: 132 ================================================================================================ Orgo — public conceptual wiki. For schemas, APIs, implementation constraints and code alignment, use the technical documentation. ================================================================================================ FILE: wiki/_Sidebar.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: af5033920ebe92dcefa584fd2b83c3200a3eddd7b862b4b35b57550be01f13e1 CONTENT_BYTES: 816 ================================================================================================ **Orgo Wiki** - [[Home]] - [[What is Orgo|What-is-Orgo]] - [[How Orgo Works|How-Orgo-Works]] - [[Cases and Tasks|Cases-and-Tasks]] - [[Signals and Workflows|Signals-and-Workflows]] - [[Routing and Labels|Routing-and-Labels]] - [[Profiles and Adaptability|Profiles-and-Adaptability]] - [[Reactivity and Escalation|Reactivity-and-Escalation]] - [[Domains and Use Cases|Domains-and-Use-Cases]] - [[Cyclic Overview and Insights|Cyclic-Overview-and-Insights]] - [[Organizations, People and Privacy|Organizations-People-and-Privacy]] - [[Offline and Resilience|Offline-and-Resilience]] - [[Interoperability]] - [[Semantic Charters|Semantic-Charters]] - [[Example Scenarios|Example-Scenarios]] - [[Glossary]] - [[FAQ]] - [[Resources]] --- Technical details belong in the Orgo documentation rather than this public wiki. ================================================================================================ FILE: wiki/Cases-and-Tasks.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: d4bab76310f1a56b64a2979bb94121942a6365baf054664417d70bc0b1b28ea3 CONTENT_BYTES: 1821 ================================================================================================ # Cases and Tasks Cases and Tasks are the two most important work objects in Orgo. ## Task: the unit of work A **Task** represents something that should be done or tracked operationally. Examples: - inspect a reported leak; - contact a person about a request; - review a document; - follow up on a support incident; - prepare a report; - distribute information to a defined audience. Every Task uses the same core lifecycle: ```text Pending ↓ In progress ├── On hold → In progress ├── Completed ├── Failed └── Escalated Pending / On hold can also be cancelled when appropriate. ``` The exact wording shown by a user interface can be friendlier, but the underlying states remain consistent. ## Case: durable context A **Case** represents a situation that may need multiple actions or continued attention. Examples: - a building problem with several repair steps; - a sensitive HR matter; - a student-support situation; - a recurring operational issue; - a request that spans several teams. A Case can remain open while multiple Tasks are created, completed or escalated around it. ## Why both are needed Without Cases, long-running situations become disconnected lists of tasks. Without Tasks, a Case can become a passive folder with no clear action. Orgo keeps the distinction explicit: ```text Case = why / context / continuing situation Task = what needs to happen ``` ## A Case is not the outside world A Case may refer to something owned by another system, but it does not become that thing. For example: ```text Orgo Case ≠ Konnaxion Topic Orgo Task ≠ Konnaxion Consultation ``` The same principle applies to other external systems: Orgo can coordinate work around an external object without copying its entire meaning into the Task/Case model. ================================================================================================ FILE: wiki/Cyclic-Overview-and-Insights.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 0b555879e54a05716cdc58617a5e13fb9e06b70c7822c3e3968953de78340eb6 CONTENT_BYTES: 1346 ================================================================================================ # Cyclic Overview and Insights Orgo is designed not only to track individual tasks, but also to help an organization **see its own operational patterns over time**. ## Insights The Insights layer summarizes and analyzes operational state. It can support views such as: - work volume; - unresolved or escalating work; - reactivity/SLA pressure; - recurring categories; - organizational or profile-level patterns. These are **read models**: they help people understand what is happening without becoming a second source of operational truth. ## Cyclic Overview A **Cyclic Overview** is a recurring review of operational activity. The exact cadence depends on the Organization Profile, but the principle is stable: ```text do work → observe outcomes → review patterns → decide whether action is needed → create governed work ``` The public idea is broader than a dashboard. It is a feedback loop between execution and organizational learning. ## Patterns become work explicitly Suppose the same type of incident repeatedly occurs in the same place. Insights may detect the pattern, but it should not silently mutate operational state. Instead: ```text pattern detected → proposed follow-up → explicit Case / Task → normal routing and accountability ``` That keeps analysis and action connected without confusing them. ================================================================================================ FILE: wiki/Domains-and-Use-Cases.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: af81b62c49840b7466ce2efe9655741e9bf6ae0a4e3eb5fa805cca5e93488c90 CONTENT_BYTES: 1834 ================================================================================================ # Domains and Use Cases Orgo is not limited to one industry or department. Domain modules add specialized context while keeping the shared Task/Case backbone. The current Orgo model includes examples for **Maintenance, HR and Education**, and the charter system also defines reusable semantic families for care, programs, operations, groups and incidents. ## Maintenance A maintenance request can add context such as: - asset; - location; - repair information; - calendar or maintenance slot. But the actual work remains a canonical Orgo Task. ```text maintenance request → Orgo Task → maintenance-specific context → normal Task lifecycle ``` ## HR A sensitive HR situation can use a Case for durable context and Tasks for the actions that follow. ```text report → Case → primary Task → HR-specific participants and context ``` This is useful because confidentiality and subject participation can remain domain-specific while assignment and work progression continue to use the shared Orgo engine. ## Education Education-support or incident work can be linked to learning groups, people and education-specific context while remaining a canonical Task. ## Why domain modules are not separate workflow engines The goal is not to make every domain identical. It is to avoid rebuilding basic operational concepts every time. A domain can have rich business rules and additional data without redefining: - what a Task is; - the Task lifecycle; - how Cases contain work; - how core routing and events operate. ## Beyond the built-in examples The same pattern can support other organizational settings when their specialized data and rules can be layered around the common work backbone. Orgo's semantic charters help describe these domains without turning every vocabulary difference into a new core schema. ================================================================================================ FILE: wiki/Example-Scenarios.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: e1a3361e5ebaafed535afb3fd5c6b4a148f3b47717956740856e0dd2f984577e CONTENT_BYTES: 1998 ================================================================================================ # Example Scenarios These examples illustrate the Orgo model without defining new domain contracts. ## 1. Facilities issue A staff member reports water leaking near an entrance. ```text report arrives → Signal → workflow evaluates severity and routing → Case: recurring/continuing facilities situation when needed → Task: inspect the leak → maintenance context links the relevant asset/location → Task is assigned and tracked → later incidents can appear in Insights as a pattern ``` The maintenance information is specialized, but the work still uses the common Orgo Task lifecycle. ## 2. Sensitive HR report A report concerns a person and requires restricted handling. ```text report → Signal → HR workflow → Case for durable confidential context → primary Task for the next required action → HR participants/context attached → visibility and authorization rules apply ``` The Person concerned by the Case does not need to be an Orgo User. ## 3. Education support A student-support concern is submitted. ```text support signal → workflow → Task → education context links the relevant person/group → assignment and follow-up ``` Education-specific context stays in the domain layer while work progression remains canonical Orgo Task state. ## 4. Repeated incident becomes organizational work Several similar incidents occur over time. ```text individual Tasks/Cases → Insights detects a recurring pattern → pattern is reviewed → explicit follow-up Case/Task is created → normal routing and accountability ``` Insights does not silently rewrite operational state. ## 5. Coordinating an external system An Orgo workflow needs an operation performed by another system. ```text Orgo Task → explicit request to external system → external system validates and acts in its own domain → result / receipt returns → Orgo reconciles the Task ``` Orgo coordinates the work without taking ownership of the external system's internal data. ================================================================================================ FILE: wiki/FAQ.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 8a1d7816d54998c0bb8287131f71fd38907be402379e8b442da1dfe4af811f71 CONTENT_BYTES: 2701 ================================================================================================ # FAQ ## Is Orgo a ticketing system? It can handle work that resembles tickets, but its model is broader. Orgo separates Signals, Cases and Tasks, adds workflow evaluation, organization profiles, routing labels and cyclic review, and supports multiple domain modules on the same core. ## Is a Case just a large Task? No. A Case is durable context for a situation. A Task is a unit of work. A Case may contain many Tasks over time. ## Does every Signal create a Task? No. A Signal is evaluated first. A workflow may ignore it, update existing work, create a Case, create one or more Tasks, route information or perform another declared action. ## Can each department define its own Task statuses? Not as a separate core lifecycle. Domain modules add context while reusing the canonical Orgo Task lifecycle. ## What are Labels for? Labels help classify and route work. They are not a replacement for authorization and should not be overloaded with every possible taxonomy concept. ## What is a broadcast label? It is an informational routing form. Broadcasting something does not automatically create mandatory work. A workflow must explicitly create a Task when action is required. ## How does Orgo adapt to different organizations? Through Organization Profiles and domain modules. Profiles tune behavior; domain modules add specialized context. ## What is Reactivity Time? It is Orgo's way of expressing how quickly work is expected to receive attention or response. The actual defaults can vary by Organization Profile. ## Does Orgo use AI to decide everything? The architecture does not depend on a heavy external LLM as its core workflow engine. Workflow rules, labels, profiles and semantic charters are designed to remain explicit and compatible with local/offline operation. ## Is Insights allowed to change Tasks automatically? Insights is primarily analytical. When a detected pattern should create operational work, that should happen explicitly through the normal Case/Task core rather than by silently rewriting operational state. ## Is Orgo part of kOA-Linux? Orgo is an ecosystem system in its own right. In a kOA-Linux deployment it can be integrated as a subsystem from the host's point of view, while Orgo remains authoritative for its own workflow state. ## Does Orgo own Konnaxion or Kristal data when it coordinates them? No. Orgo may track work, external references and results, but the external system remains authoritative for its own domain. ## Is Orgo an ERP? No. It may coordinate work around ERP-like processes, but it is not intended to become the authoritative accounting, payroll or inventory system simply because those processes create Tasks. ================================================================================================ FILE: wiki/Glossary.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 766ecc95f91823a74f78b8f8e322a4e2c31ee21e50e7dbbcc44bd8024e617b8d CONTENT_BYTES: 1884 ================================================================================================ # Glossary This page uses public-facing definitions. The technical documentation contains the exact contracts and schemas. ## Organization The tenant and operational boundary in Orgo. Cases, Tasks, profiles and permissions belong to an Organization. ## Signal An input that may require work: an email, form, API call, event, offline input or similar trigger. A Signal is not automatically a Task. ## Case A durable container for a situation, its context and related work over time. ## Task The canonical unit of work in Orgo. ## Workflow Rules that evaluate signals or operational context and determine what actions should follow. ## Label A compact routing/classification address used to help place work in the right operational context. ## Profile Organization-specific behavioral configuration, including defaults for reactivity, transparency, retention, pattern sensitivity and automation. ## Domain module A specialized layer for a domain such as Maintenance, HR or Education that adds context while reusing the common Task/Case engine. ## Insight A derived analytical view over operational activity. ## Cyclic Overview A recurring review loop that turns operational history into organizational learning and, when appropriate, new governed work. ## User An authenticated Orgo actor/account. ## Person A human subject/profile represented in Orgo, whether or not the person has a User account. ## Charter A semantic vocabulary/reference layer that helps Orgo reuse and refine common concepts across domains. ## Receipt Structured evidence that an external or internal operation was accepted, rejected or executed. It helps Orgo reconcile workflow without replacing the authoritative state it refers to. ## Ecosystem system A system with its own significant domain authority and boundaries. Orgo is one ecosystem system in the kOA Digital Ecosystem. ================================================================================================ FILE: wiki/Home.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 0679834eec057ebe24d8024ba81fea233fdd4bc891b991df7908b24c1b49b4a3 CONTENT_BYTES: 3078 ================================================================================================ # Orgo **Orgo is a coordination system for turning messy signals into clear, accountable work.** Organizations rarely receive work in a neat format. A request may begin as an email, a form, a conversation, a report, a recurring issue or a system event. Orgo gives these signals a common operational language so they can be understood, routed, acted on and reviewed without forcing every organization into the same workflow. A useful way to think about Orgo is as an **operational nervous system**: ```text something happens ↓ Orgo receives the signal ↓ context is organized into a Case when needed ↓ action becomes one or more Tasks ↓ work is routed, tracked and escalated ↓ patterns become visible through Insights ↓ new work can be created when action is needed ``` Orgo is multi-tenant: each **Organization** has its own work, people, policies and behavioral profile. ## What makes Orgo different Orgo is built around a few shared ideas rather than a separate workflow engine for every department: - **Task** is the common unit of work. - **Case** keeps durable context around related work. - **Signals** are inputs, not automatically work items. - **Workflows** evaluate what should happen. - **Labels** help route and classify work. - **Profiles** adapt Orgo to different organizations without changing the core model. - **Insights** help organizations notice recurring patterns and review how work is actually flowing. - **Domain modules** add specialized context while reusing the same Task/Case backbone. This lets a maintenance team, a school, a care organization, an association or an internal operations team use the same underlying coordination model while keeping their own vocabulary and rules. ## Start here - [[What is Orgo|What-is-Orgo]] - [[How Orgo Works|How-Orgo-Works]] - [[Cases and Tasks|Cases-and-Tasks]] - [[Signals and Workflows|Signals-and-Workflows]] - [[Routing and Labels|Routing-and-Labels]] - [[Profiles and Adaptability|Profiles-and-Adaptability]] - [[Reactivity and Escalation|Reactivity-and-Escalation]] - [[Domains and Use Cases|Domains-and-Use-Cases]] - [[Cyclic Overview and Insights|Cyclic-Overview-and-Insights]] - [[Organizations, People and Privacy|Organizations-People-and-Privacy]] - [[Interoperability]] - [[Semantic Charters|Semantic-Charters]] - [[Glossary]] - [[Example Scenarios|Example-Scenarios]] - [[FAQ]] ## What Orgo is not Orgo is not meant to replace every business system around it. It is not, by itself: - a payroll system; - an accounting ERP; - a casual chat application; - a domain database for every external system; - a knowledge-truth engine; - a civic decision system. Orgo coordinates work and keeps operational state. When another system owns the underlying domain, Orgo tracks and orchestrates the work around it rather than silently taking ownership of that system's data. --- **Technical implementation details live in the Orgo documentation.** This wiki focuses on the public-facing concepts and how Orgo is meant to be understood and used. ================================================================================================ FILE: wiki/How-Orgo-Works.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: c62d68c72889bf38b8c99331c54dca60cb3e16c17e34186c3b208f9451dfae5f CONTENT_BYTES: 1997 ================================================================================================ # How Orgo Works Orgo follows a simple operational loop: ```text Listen → Understand → Organize → Route → Act → Review → Learn ``` ## 1. Listen A **Signal** enters Orgo. A signal may be a request, report, message, form submission, API call, system event, offline input or scheduled trigger. A signal is only an input. Orgo does not assume every signal deserves a new Task. ## 2. Understand Orgo evaluates the signal in the context of the Organization: - What kind of situation is this? - Does it belong to an existing Case? - Does it require action? - Which workflow rules apply? - How urgent is it? - Who or what area should receive it? ## 3. Organize If durable context is needed, Orgo can use a **Case**. If action is required, Orgo creates one or more **Tasks**. ```text Case = the situation / continuing context Task = a concrete unit of work ``` A Case may contain many Tasks over time. ## 4. Route A Task can be classified and routed using an Orgo **Label**, organization roles and workflow rules. Routing is deterministic enough to be understood and reviewed. It is not meant to be a mysterious recommendation layer. ## 5. Act The Task follows the common Orgo lifecycle. It can be assigned, started, paused, escalated, completed, failed or cancelled according to the core rules. Domain-specific information remains attached without replacing this common lifecycle. ## 6. Review Orgo keeps the operational history needed to understand what happened: - task events; - assignments; - comments; - workflow transitions; - audit/security information where applicable. ## 7. Learn The **Insights** layer can detect trends, recurring issues and operational pressure. A pattern is not automatically an instruction. When action is required, Orgo brings it back into the governed workflow: ```text pattern → explicit work proposal → Case / Task → normal routing and lifecycle ``` This closes the loop between day-to-day work and organizational learning. ================================================================================================ FILE: wiki/Interoperability.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 38e0b4b34248d60c19f9d0039c08808210a0964f0823a758bacfbf0ba6912c8e CONTENT_BYTES: 1828 ================================================================================================ # Interoperability Orgo is designed to coordinate work **with** other systems rather than absorb them. This matters in the wider kOA Digital Ecosystem, where different systems have different responsibilities. ## The basic rule ```text Orgo owns workflow state. The other system owns its own domain state. ``` An Orgo Task can request an operation, track its progress and record a receipt without becoming the source of truth for the external object. ## Konnaxion Konnaxion owns its civic/public domain. A future integration may allow Orgo to coordinate work related to a consultation, deliberation or civic process, but: ```text Orgo Case ≠ Konnaxion Topic Orgo Task ≠ Konnaxion Consultation ``` ## Kristal Kristal owns epistemic artifacts and their semantics. Orgo may coordinate review or other work around a Kristal operation, but completing an Orgo Task does not automatically mean a Kristal assertion has been validated or recognized. ## SemantiK Architect SemantiK Architect owns language-generation planning and realization. Orgo can request generated output as part of a workflow, but generated language is not the same thing as Orgo workflow state. ## kOA-Linux When Orgo runs within kOA-Linux, Orgo keeps ownership of its Cases, Tasks and workflows. kOA-Linux owns the local platform boundary: host resources, service lifecycle, privilege mediation, recovery and other operating-system responsibilities. ## Why this separation matters It prevents one integration from turning into a shared database where nobody knows which system is authoritative. A healthy integration looks more like: ```text Orgo requests → external system validates and acts → result / event / receipt returns → Orgo reconciles its own workflow ``` The same principle applies to other external tools and services. ================================================================================================ FILE: wiki/Offline-and-Resilience.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 075d547307f7a76b9d5bc07a486dc750189b94509982e4b971f6f619a4934b84 CONTENT_BYTES: 1115 ================================================================================================ # Offline and Resilience Orgo is designed with **offline and local operation** in mind. That does not mean every external integration is magically available without a network. It means Orgo's own operational model can distinguish local work from synchronization and can represent offline/sync inputs explicitly. ## Offline signals Offline or synchronized input is treated as a Signal, then processed through normal Orgo rules. ```text local/offline input → synchronization or ingestion → organization scope → workflow evaluation → Case / Task when appropriate ``` Offline sync is not a shortcut around the normal Task/Case lifecycle. ## Resilience through explicit state Because Tasks, Cases, assignments and events are explicit, an organization can reason about what is pending, what has been completed and what still needs reconciliation after connectivity returns. ## External systems If a workflow depends on another system that is unavailable, Orgo can still retain its own workflow context. The external operation remains incomplete until the external owner actually accepts or performs it. ================================================================================================ FILE: wiki/Organizations-People-and-Privacy.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 23abd2ffe4dee17c9eab8be7989b8f9063e3951bfaadcdb35e3dd40ec30b5c96 CONTENT_BYTES: 1439 ================================================================================================ # Organizations, People and Privacy Orgo is multi-tenant. The **Organization** is the primary operational boundary. ## Organization An Organization has its own: - Cases and Tasks; - profile and configuration; - roles and permissions; - people and user accounts; - workflows and operational history; - analytical views. One organization's identifiers must not become a shortcut into another organization's data. ## User and Person are different Orgo distinguishes a **User account** from a **Person profile**. ### User A User is an actor who can authenticate and perform actions in Orgo. ### Person A Person is a human subject represented in operational context. A Person might be: - an employee; - a student; - a patient or care recipient; - a volunteer; - a requester; - another person involved in a Case. That person may never log in to Orgo. ```text User = actor/account Person = subject/profile ``` This distinction is especially important in HR, care and education contexts. ## Visibility and authorization Orgo can classify work by visibility and route it through labels, but those mechanisms are not substitutes for authorization. Sensitive work should remain organization-scoped and role/permission-aware. ## External identities When Orgo refers to an object or person owned by another system, the relationship should remain explicit. Orgo stores only the references and operational context it actually needs. ================================================================================================ FILE: wiki/Profiles-and-Adaptability.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 5d0b2f9a3d9c05cfd0d18a2e2ddc019b83a724864166420af5dde7fbd2b000b3 CONTENT_BYTES: 1147 ================================================================================================ # Profiles and Adaptability Orgo is designed to serve organizations with very different operating rhythms without forking the core system for each one. The main mechanism is the **Organization Profile**. ## What a Profile changes A Profile can tune defaults such as: - expected reactivity; - transparency and visibility defaults; - escalation behavior; - sensitivity to recurring patterns; - retention behavior; - automation and review cadence. A fast-response environment can therefore behave differently from a volunteer association while both still use the same Task and Case model. ## What a Profile does not change A Profile does not create a new Orgo schema or a separate Task lifecycle. ```text same core model + different profile = different operating behavior ``` This is one reason Orgo can be adapted across domains without becoming a collection of unrelated applications. ## Profiles and domain modules Profiles tune organizational behavior. Domain modules add specialized context. They solve different problems: ```text Profile → how this Organization operates Domain module → what this kind of work means ``` ================================================================================================ FILE: wiki/Reactivity-and-Escalation.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 30c2f0f75cedd3b2092b7f7ad1edd1412fb6e2051a33c240ec79f1aa6ca54ffd CONTENT_BYTES: 1595 ================================================================================================ # Reactivity and Escalation Orgo distinguishes **reactivity** from a simple final deadline. A deadline answers: > When should this work be finished? Reactivity asks an earlier question: > How quickly should this work receive attention? That distinction matters in organizations where silence itself is a problem. ## Reactivity A Task can carry an expected reactivity window derived from its context and the Organization Profile. Examples of the idea: - a critical operational incident may require attention very quickly; - a routine internal request may tolerate a longer response window; - a volunteer organization may deliberately use slower defaults than an emergency-oriented operation. The important point is not one universal number. The Organization defines what “responsive” means for its own context. ## Escalation When work is not receiving the expected attention, Orgo can raise its operational visibility or routing level according to explicit rules. Conceptually: ```text Task created → expected reactivity window → no sufficient response → escalation rule applies → Task remains governed work with a visible escalation state ``` Escalation does not create a second Task lifecycle. It is part of the common operational model. ## Why this is useful Organizations often discover problems only after a final due date has been missed. Reactivity gives them a way to notice much earlier that work has stalled. Combined with Cyclic Overview and Insights, this also makes it possible to distinguish an isolated delay from a recurring organizational pattern. ================================================================================================ FILE: wiki/Resources.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 320daacdd6541ed07914f29644ecaa09a062d3feceeb7cdde2cbe45209ab5a22 CONTENT_BYTES: 423 ================================================================================================ # Resources ## Public overview presentation The existing Orgo wiki referenced this public presentation: https://administrative-efficienc-0u6vhrh.gamma.site/ ## Technical documentation The Orgo technical documentation contains the detailed architecture, database schema, Task/Case contracts, APIs, domain-module contracts and implementation alignment notes. This wiki intentionally stays at a conceptual/public level. ================================================================================================ FILE: wiki/Routing-and-Labels.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 2431441d5a285f0d5a0e27c122c512db75275e27c35eee4612acb51a9f594f8e CONTENT_BYTES: 1299 ================================================================================================ # Routing and Labels Orgo uses **Labels** as a compact routing and classification language. A label can express three things: 1. a vertical or organizational scope; 2. a category and subcategory; 3. an optional horizontal role. The general form is: ```text .[.] ``` Example: ```text 100.94.Operations.Safety ``` The precise codes are configured and documented technically, but public users mainly need to understand the idea: **a label is an address for operational context**. ## Labels are not permissions A label can help determine where work belongs, but it does not replace authorization. Seeing a routing label does not automatically grant access to the underlying Case or Task. ## One canonical routing label Orgo keeps one canonical routing label on the work object rather than trying to encode every possible taxonomy dimension into one string. Additional classification can live in metadata, tags or domain-specific structures. ## Broadcast labels Some label bases represent broadcasts. A broadcast is informational by default: ```text broadcast ≠ mandatory Task ``` If the information requires action, a workflow must explicitly create or assign that work. This prevents announcements from silently becoming obligations. ================================================================================================ FILE: wiki/Semantic-Charters.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 6f0cafe14b8e2210388e9263ed20c36b6d5ee66a356ac9f8c18e487bc76e8189 CONTENT_BYTES: 1719 ================================================================================================ # Semantic Charters Orgo's **Semantic Charters** provide a reusable vocabulary layer for describing organizational concepts across different domains. They are not another workflow engine and they do not replace Cases, Tasks or labels. ## Why Charters exist Different organizations often use different words for similar concepts. Orgo's charter model helps keep domain vocabulary interoperable without forcing every organization into exactly the same terminology. The charter system can align selected concepts with **Wikidata-compatible identifiers** while keeping Orgo's own organizational relationships focused on workflow needs. ## Three levels The current charter model is layered: ```text General ↓ Family ↓ Domain specialization ``` Examples of families include: - care; - programs; - operations; - groups; - incidents. Domain specializations can refine these families for contexts such as hospitals, schools, social services, manufacturing, transport/logistics, facilities, sports groups, associations or IT help desks. ## What gets reused Orgo can reuse selected public identifiers for concepts and properties where they already fit. It can also define its own refinements when organizational workflow needs a more precise relation. The public principle is: > **Reuse shared meaning where it fits; specialize only where Orgo needs a clearer operational relation.** ## Offline-friendly by design The charter concept is compatible with a filtered local subset of public semantic data. Orgo does not need to import the entire Wikidata graph just to use common identifiers. This keeps semantic assistance useful in local/offline environments while preserving Orgo's own workflow model. ================================================================================================ FILE: wiki/Signals-and-Workflows.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: b8bfd927e0c739bd796ea032ec059143c50714993a0a641aa6f4bec5bc7e0ca4 CONTENT_BYTES: 1550 ================================================================================================ # Signals and Workflows A major Orgo principle is that **an incoming signal is not automatically a task**. ## Signals A Signal is something Orgo receives that may require interpretation or action. Examples include: - a message or email; - an API request; - a form submission; - a system-generated event; - a timer; - an offline/synchronized input. Signals can carry structured context, but they do not decide their own operational outcome. ## Workflows A **Workflow** evaluates a signal or existing operational context and determines which actions should follow. Conceptually: ```text Signal + Organization context ↓ Workflow rules ↓ resolved actions ↓ Tasks / Cases / routing / notification / metadata changes ``` Typical actions can include creating work, updating work, routing it, escalating it, attaching metadata or notifying someone. ## Why evaluation and execution are separate Orgo distinguishes **deciding what should happen** from **performing the side effect**. That matters because it allows a workflow to be simulated: ```text same input + same rules → same resolved actions → no mutation in simulation mode ``` This makes workflows easier to inspect, test and explain. ## Workflows do not own everything they touch If a workflow eventually calls another system, that system still decides whether the requested operation is valid in its own domain. Orgo can coordinate the process and reconcile the result, but it does not gain direct write access to another system's internal data. ================================================================================================ FILE: wiki/What-is-Orgo.md AUTHORITY: reference CONTENT_ROLE: navigation CONTENT_SHA256: 1398dcfbe5504f72984d6c9364ec0cf83bccc96838f120ec5062a732214dc3f6 CONTENT_BYTES: 2201 ================================================================================================ # What is Orgo? Orgo is a **multi-tenant workflow and coordination system**. Its purpose is simple to state: take the many things that happen around an organization and turn the ones that require attention into structured, traceable work. ## The problem Orgo addresses Organizations receive signals from many places: - email; - forms and APIs; - staff or community reports; - operational systems; - periodic reviews; - offline synchronization; - timers and recurring checks. Without a common structure, the result is usually fragmentation: different teams invent different status labels, important context is lost between tools, and recurring problems are hard to see. Orgo standardizes the operational layer without forcing every domain to become identical. ## One backbone, many domains Orgo uses the same shared work backbone across domains: ```text Organization ├── Cases │ └── Tasks ├── Workflows ├── Labels ├── Profile └── Insights ``` A maintenance task and an education-support task can therefore share the same basic operational lifecycle while keeping very different domain-specific details. ## Orgo owns workflow state This is an important boundary. Orgo is authoritative for things such as: - whether an Orgo Task is pending, in progress or completed; - who is assigned to that Task; - which Case groups related work; - the routing label attached to the work; - escalation and reactivity state; - Orgo workflow execution and audit information. Orgo does **not** become the owner of another system's internal state simply because a Task refers to it. For example, if Orgo coordinates work related to a Konnaxion consultation or a Kristal artifact, the Task can reference that external object while the external system remains authoritative for its own domain. ## A coordination system, not a department-specific app Orgo is designed to remain useful across different organizational settings. Specialized domain modules can add context for Maintenance, HR, Education and other areas, but they reuse the same core work model. That is the central design idea: > **Different domains, shared operational grammar.** ================================================================================================ FILE: apps/api/README.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: edd1819af6b8f652719c0a4f0b71905fe35b80e9bfd24ae5f9433b916b400c50 CONTENT_BYTES: 206 ================================================================================================ # Orgo API and worker See the root README for setup and `docs/Technical-Reference/API_IMPLEMENTED.md` for the active HTTP contract. The API and worker share RuntimeModule, PostgreSQL and the same release. ================================================================================================ FILE: apps/web/README.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: e47c0bb330e89cd9c0e4a244509de0ac6967c7d20be5f54692738e2856fa3933 CONTENT_BYTES: 289 ================================================================================================ # Orgo web One owner-managed React application, served standalone by Next. Profiles compose routes in `src/orgo/profiles.ts`; `hosted-entry.tsx` exports the same component for a host that supplies routing. Native Koali admission is a separate integration validation. See the root README. ================================================================================================ FILE: CODE_SNAPSHOT_MANIFEST.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 3adeddce2bb6fc26e6bb2013744bed7c12bb464ac4c50f953d1cde7a7a28a728 CONTENT_BYTES: 15646 ================================================================================================ > Historical inventory of the uploaded snapshot. Active sources have since changed; use DELIVERY_MANIFEST.json and IMPLEMENTATION_STATUS.md. # Code snapshot - generated_at: 2026-09-08T16:53:23.196958 - repository: Orgo - archive_layout: repository-relative paths ## Snapshot files - `.dockerignore` (241 bytes) - `.github/workflows/api.yaml` (1277 bytes) - `.github/workflows/web.yaml` (1116 bytes) - `.gitignore` (449 bytes) - `apps/api/.eslintrc.js` (688 bytes) - `apps/api/.prettierrc` (54 bytes) - `apps/api/Dockerfile` (1370 bytes) - `apps/api/nest-cli.json` (68 bytes) - `apps/api/package.json` (2946 bytes) - `apps/api/prisma/migrations/20220307034109_initial_migrate/migration.sql` (241 bytes) - `apps/api/prisma/migrations/20251127134632_init/migration.sql` (69937 bytes) - `apps/api/prisma/migrations/migration_lock.toml` (128 bytes) - `apps/api/prisma/schema.prisma` (59543 bytes) - `apps/api/README.md` (3412 bytes) - `apps/api/src/app.controller.spec.ts` (791 bytes) - `apps/api/src/app.controller.ts` (320 bytes) - `apps/api/src/app.module.ts` (2627 bytes) - `apps/api/src/app.service.ts` (190 bytes) - `apps/api/src/config/environment-variables.ts` (229 bytes) - `apps/api/src/main.ts` (860 bytes) - `apps/api/src/orgo/backbone/identity/dto/link-user-person.dto.ts` (1066 bytes) - `apps/api/src/orgo/backbone/identity/identity-link.controller.ts` (6636 bytes) - `apps/api/src/orgo/backbone/identity/identity-link.module.ts` (890 bytes) - `apps/api/src/orgo/backbone/identity/identity-link.service.ts` (19091 bytes) - `apps/api/src/orgo/backbone/organizations/dto/create-organization.dto.ts` (2971 bytes) - `apps/api/src/orgo/backbone/organizations/dto/update-organization.dto.ts` (2915 bytes) - `apps/api/src/orgo/backbone/organizations/organization.controller.ts` (3382 bytes) - `apps/api/src/orgo/backbone/organizations/organization.module.ts` (1114 bytes) - `apps/api/src/orgo/backbone/organizations/organization.service.ts` (18102 bytes) - `apps/api/src/orgo/backbone/persons/dto/upsert-person-profile.dto.ts` (2288 bytes) - `apps/api/src/orgo/backbone/persons/person-profile.controller.ts` (11977 bytes) - `apps/api/src/orgo/backbone/persons/person-profile.module.ts` (709 bytes) - `apps/api/src/orgo/backbone/persons/person-profile.service.ts` (11024 bytes) - `apps/api/src/orgo/backbone/rbac/dto/assign-permission.dto.ts` (857 bytes) - `apps/api/src/orgo/backbone/rbac/dto/create-role.dto.ts` (1645 bytes) - `apps/api/src/orgo/backbone/rbac/permission.service.ts` (7586 bytes) - `apps/api/src/orgo/backbone/rbac/rbac.controller.ts` (10827 bytes) - `apps/api/src/orgo/backbone/rbac/rbac.module.ts` (1330 bytes) - `apps/api/src/orgo/backbone/rbac/role.service.ts` (6374 bytes) - `apps/api/src/orgo/config/config.controller.ts` (10865 bytes) - `apps/api/src/orgo/config/config.module.ts` (987 bytes) - `apps/api/src/orgo/config/config.service.ts` (22876 bytes) - `apps/api/src/orgo/config/feature-flag.controller.ts` (11395 bytes) - `apps/api/src/orgo/config/feature-flag.service.ts` (24522 bytes) - `apps/api/src/orgo/config/org-profile.controller.ts` (12376 bytes) - `apps/api/src/orgo/config/org-profile.service.ts` (36849 bytes) - `apps/api/src/orgo/core/alerts/alerting.service.ts` (11912 bytes) - `apps/api/src/orgo/core/cases/case.controller.ts` (14451 bytes) - `apps/api/src/orgo/core/cases/case.module.ts` (788 bytes) - `apps/api/src/orgo/core/cases/case.service.ts` (15902 bytes) - `apps/api/src/orgo/core/cases/dto/create-case.dto.ts` (5748 bytes) - `apps/api/src/orgo/core/cases/dto/update-case-status.dto.ts` (939 bytes) - `apps/api/src/orgo/core/database/database.service.ts` (10819 bytes) - `apps/api/src/orgo/core/database/repository-factory.service.ts` (10787 bytes) - `apps/api/src/orgo/core/email/email-ingest.service.ts` (27711 bytes) - `apps/api/src/orgo/core/email/email-parser.service.ts` (20208 bytes) - `apps/api/src/orgo/core/email/email-router.service.ts` (33688 bytes) - `apps/api/src/orgo/core/email/email-validator.service.ts` (10616 bytes) - `apps/api/src/orgo/core/email/email.controller.ts` (9657 bytes) - `apps/api/src/orgo/core/email/email.module.ts` (1956 bytes) - `apps/api/src/orgo/core/email/email.service.ts` (15865 bytes) - `apps/api/src/orgo/core/functional-ids.ts` (14065 bytes) - `apps/api/src/orgo/core/health/health.controller.ts` (3641 bytes) - `apps/api/src/orgo/core/health/worker-health.service.ts` (8624 bytes) - `apps/api/src/orgo/core/labels/label-routing.service.ts` (10509 bytes) - `apps/api/src/orgo/core/labels/label.service.ts` (11260 bytes) - `apps/api/src/orgo/core/labels/labels.module.ts` (515 bytes) - `apps/api/src/orgo/core/labels/routing-rule.service.ts` (11961 bytes) - `apps/api/src/orgo/core/logging/log.service.ts` (25894 bytes) - `apps/api/src/orgo/core/logging/logger.module.ts` (1462 bytes) - `apps/api/src/orgo/core/metrics/metrics.service.ts` (17956 bytes) - `apps/api/src/orgo/core/notifications/notification.controller.ts` (7002 bytes) - `apps/api/src/orgo/core/notifications/notification.module.ts` (841 bytes) - `apps/api/src/orgo/core/notifications/notification.service.ts` (40229 bytes) - `apps/api/src/orgo/core/offline/offline-sync.module.ts` (716 bytes) - `apps/api/src/orgo/core/offline/sync.service.ts` (19601 bytes) - `apps/api/src/orgo/core/signals/dto/create-signal.dto.ts` (6108 bytes) - `apps/api/src/orgo/core/signals/signal-ingest.service.ts` (20108 bytes) - `apps/api/src/orgo/core/signals/signal.controller.ts` (3791 bytes) - `apps/api/src/orgo/core/signals/signals.module.ts` (599 bytes) - `apps/api/src/orgo/core/tasks/dto/create-task.dto.ts` (5785 bytes) - `apps/api/src/orgo/core/tasks/dto/update-task-status.dto.ts` (1251 bytes) - `apps/api/src/orgo/core/tasks/task-events.gateway.ts` (10833 bytes) - `apps/api/src/orgo/core/tasks/task-events.service.ts` (13927 bytes) - `apps/api/src/orgo/core/tasks/task.controller.ts` (9449 bytes) - `apps/api/src/orgo/core/tasks/task.module.ts` (388 bytes) - `apps/api/src/orgo/core/tasks/task.service.ts` (36897 bytes) - `apps/api/src/orgo/core/validation/config-validation.service.ts` (8937 bytes) - `apps/api/src/orgo/core/validation/metadata.service.ts` (7906 bytes) - `apps/api/src/orgo/core/validation/payload-validation.pipe.ts` (12286 bytes) - `apps/api/src/orgo/core/workflow/escalation.service.ts` (32655 bytes) - `apps/api/src/orgo/core/workflow/workflow-engine.service.ts` (36604 bytes) - `apps/api/src/orgo/core/workflow/workflow.controller.ts` (5957 bytes) - `apps/api/src/orgo/core/workflow/workflow.module.ts` (652 bytes) - `apps/api/src/orgo/domain/domain-task.factory.ts` (7711 bytes) - `apps/api/src/orgo/domain/domain-workflow.service.ts` (17516 bytes) - `apps/api/src/orgo/domain/education/education.controller.ts` (12104 bytes) - `apps/api/src/orgo/domain/education/education.module.ts` (342 bytes) - `apps/api/src/orgo/domain/education/education.service.ts` (29771 bytes) - `apps/api/src/orgo/domain/hr/hr.controller.ts` (6971 bytes) - `apps/api/src/orgo/domain/hr/hr.module.ts` (551 bytes) - `apps/api/src/orgo/domain/hr/hr.service.ts` (24680 bytes) - `apps/api/src/orgo/domain/hr/hr.service.ts.BAK` (29187 bytes) - `apps/api/src/orgo/domain/maintenance/maintenance.controller.ts` (2634 bytes) - `apps/api/src/orgo/domain/maintenance/maintenance.module.ts` (5329 bytes) - `apps/api/src/orgo/domain/maintenance/maintenance.service.ts` (19075 bytes) - `apps/api/src/orgo/insights/cache/insights-cache-warmup.service.ts` (8155 bytes) - `apps/api/src/orgo/insights/export/analytics-export.service.ts` (10912 bytes) - `apps/api/src/orgo/insights/insights-cache-warmup.service.ts` (10855 bytes) - `apps/api/src/orgo/insights/insights.module.ts` (1417 bytes) - `apps/api/src/orgo/insights/pattern-detection.service.ts` (26889 bytes) - `apps/api/src/orgo/insights/patterns/pattern-detection.service.ts` (26394 bytes) - `apps/api/src/orgo/insights/reports/reports.controller.ts` (5979 bytes) - `apps/api/src/orgo/insights/reports/reports.service.ts` (19965 bytes) - `apps/api/src/orgo/orgo.module.ts` (1496 bytes) - `apps/api/src/orgo/security/audit/audit-trail.service.ts` (7357 bytes) - `apps/api/src/orgo/security/auth/auth.guard.ts` (7632 bytes) - `apps/api/src/orgo/security/auth/auth.module.ts` (2286 bytes) - `apps/api/src/orgo/security/auth/auth.service.ts` (15032 bytes) - `apps/api/src/orgo/security/compliance/compliance-export.service.ts` (13754 bytes) - `apps/api/src/orgo/security/logging/log-query.service.ts` (12925 bytes) - `apps/api/src/orgo/security/privacy/privacy.service.ts` (12846 bytes) - `apps/api/src/orgo/security/rbac/rbac.service.ts` (10735 bytes) - `apps/api/src/persistence/persistence.module.ts` (212 bytes) - `apps/api/src/persistence/prisma/prisma.service.spec.ts` (478 bytes) - `apps/api/src/persistence/prisma/prisma.service.ts` (262 bytes) - `apps/api/test/app.e2e-spec.ts` (654 bytes) - `apps/api/test/jest-e2e.json` (192 bytes) - `apps/api/tsconfig.build.json` (153 bytes) - `apps/api/tsconfig.json` (119 bytes) - `apps/api/webpack-hmr.config.js` (739 bytes) - `apps/web/.env.example` (0 bytes) - `apps/web/.eslintrc.js` (51 bytes) - `apps/web/Dockerfile` (1085 bytes) - `apps/web/jest.config.js` (769 bytes) - `apps/web/jest.setup.js` (306 bytes) - `apps/web/next-env.d.ts` (206 bytes) - `apps/web/next.config.js` (119 bytes) - `apps/web/package.json` (1015 bytes) - `apps/web/pages/_app.tsx` (1034 bytes) - `apps/web/pages/index.tsx` (364 bytes) - `apps/web/postcss.config.js` (52 bytes) - `apps/web/README.md` (1399 bytes) - `apps/web/src/common/.gitkeep` (0 bytes) - `apps/web/src/orgo/core/functional-ids.ts` (4861 bytes) - `apps/web/src/orgo/hooks/useTaskEventStream.ts` (10335 bytes) - `apps/web/src/orgo/types/case.ts` (2876 bytes) - `apps/web/src/orgo/types/insights.ts` (11796 bytes) - `apps/web/src/orgo/types/organization.ts` (7892 bytes) - `apps/web/src/orgo/types/permission.ts` (3596 bytes) - `apps/web/src/orgo/types/person.ts` (2670 bytes) - `apps/web/src/orgo/types/profile.ts` (10024 bytes) - `apps/web/src/orgo/types/role.ts` (4382 bytes) - `apps/web/src/orgo/types/task.ts` (4196 bytes) - `apps/web/src/providers/AppProviders.tsx` (530 bytes) - `apps/web/src/screens/admin/.gitkeep` (0 bytes) - `apps/web/src/screens/admin/cases/AdminCaseOverviewPage.tsx` (22076 bytes) - `apps/web/src/screens/admin/insights/InsightsOverviewPage.tsx` (13230 bytes) - `apps/web/src/screens/admin/org/OrgProfileSettingsPage.tsx` (15068 bytes) - `apps/web/src/screens/admin/profiles/OrgProfileSettingsPage.tsx` (16563 bytes) - `apps/web/src/screens/admin/tasks/AdminTaskOverviewPage.tsx` (26129 bytes) - `apps/web/src/screens/auth/login/login.test.tsx` (165 bytes) - `apps/web/src/screens/auth/login/login.tsx` (1752 bytes) - `apps/web/src/screens/common/.gitkeep` (0 bytes) - `apps/web/src/screens/employee/.gitkeep` (0 bytes) - `apps/web/src/screens/insights/InsightsOverviewPage.tsx` (19550 bytes) - `apps/web/src/store/index.ts` (719 bytes) - `apps/web/src/store/services/api.ts` (412 bytes) - `apps/web/src/store/services/orgoApi.ts` (31562 bytes) - `apps/web/src/styles/global.css` (62 bytes) - `apps/web/tailwind.config.js` (53 bytes) - `apps/web/tsconfig.json` (148 bytes) - `charters/care.json` (2455 bytes) - `charters/care_hospital.json` (1700 bytes) - `charters/care_nursing_home.json` (986 bytes) - `charters/care_school.json` (1285 bytes) - `charters/care_social_services.json` (852 bytes) - `charters/general.json` (4051 bytes) - `charters/groups.json` (971 bytes) - `charters/groups_associations.json` (617 bytes) - `charters/groups_sports.json` (796 bytes) - `charters/incidents.json` (1535 bytes) - `charters/incidents_it_helpdesk.json` (591 bytes) - `charters/incidents_sst.json` (594 bytes) - `charters/operations.json` (2409 bytes) - `charters/operations_facilities.json` (900 bytes) - `charters/operations_manufacturing.json` (840 bytes) - `charters/operations_transport_logistics.json` (1028 bytes) - `charters/programs.json` (1734 bytes) - `charters/programs_government.json` (1149 bytes) - `charters/programs_humanitarian.json` (1521 bytes) - `concat_orgo.py` (8319 bytes) - `docker-compose.yml` (1557 bytes) - `docs/README.md` (3628 bytes) - `docs/Technical-Reference/Architecture upgrade(to do)/OPS-001_AI_Resilience_Strategy.md` (6356 bytes) - `docs/Technical-Reference/Architecture upgrade(to do)/REF-001_Configuration_Manifest.md` (5200 bytes) - `docs/Technical-Reference/Architecture upgrade(to do)/RFC-001_Nervous_System_Upgrade.md` (7988 bytes) - `docs/Technical-Reference/Architecture upgrade(to do)/SPEC-001_Input_SenTient_ACL.md` (6937 bytes) - `docs/Technical-Reference/Architecture upgrade(to do)/SPEC-002_Output_Architect_Outbox.md` (8052 bytes) - `docs/Technical-Reference/Boilerplate_Turborepo.md` (2348 bytes) - `docs/Technical-Reference/BOUNDARIES_AND_OWNERSHIP.md` (5599 bytes) - `docs/Technical-Reference/CODE_ALIGNMENT_NOTES.md` (19210 bytes) - `docs/Technical-Reference/CONTRACTS.md` (6444 bytes) - `docs/Technical-Reference/eliteUserList_clean.csv` (39039 bytes) - `docs/Technical-Reference/GENERALinstructionsForAI.txt` (4190 bytes) - `docs/Technical-Reference/Glossary-Letters.txt` (2905 bytes) - `docs/Technical-Reference/GLOSSARY.md` (5487 bytes) - `docs/Technical-Reference/HowToStartAndEnter.txt` (1212 bytes) - `docs/Technical-Reference/Semantic-Charters.md` (7138 bytes) - `docs/Technical-Reference/TARGET_ARCHITECTURE.md` (17058 bytes) - `docs/Technical-Reference/UI_AND_KOALI_INTEGRATION.md` (11697 bytes) - `docs/Technical-Reference/v3/1-Orgo v3 - Database Schema Reference.md` (5612 bytes) - `docs/Technical-Reference/v3/1-orgo-database-schema-reference.md` (47606 bytes) - `docs/Technical-Reference/v3/2-Orgo v3 - Architecture and Invariants.md` (8752 bytes) - `docs/Technical-Reference/v3/2-orgo-documentation-index.md` (31142 bytes) - `docs/Technical-Reference/v3/3-Orgo v3 - Task Case and Workflow Contract.md` (5841 bytes) - `docs/Technical-Reference/v3/3-orgo-full-stack-technical-spec.md` (28392 bytes) - `docs/Technical-Reference/v3/4-Orgo v3 - Domain Modules.md` (3091 bytes) - `docs/Technical-Reference/v3/4-orgo-functional-code-name-inventory.md` (46327 bytes) - `docs/Technical-Reference/v3/5-Orgo v3 - Labels Profiles and Cyclic Overview.md` (1931 bytes) - `docs/Technical-Reference/v3/5-orgo-Core-Services-Specification.md` (40973 bytes) - `docs/Technical-Reference/v3/6-Orgo v3 - Insights and Analytics.md` (1969 bytes) - `docs/Technical-Reference/v3/6-orgo-insights-module-config-parameters.md` (29951 bytes) - `docs/Technical-Reference/v3/7-Orgo v3 - API Surface.md` (3481 bytes) - `docs/Technical-Reference/v3/7-orgo-organization-profiles-and-cyclic-overview.md` (21619 bytes) - `docs/Technical-Reference/v3/8-Orgo v3 - Documentation Index.md` (1543 bytes) - `docs/Technical-Reference/v3/8-orgo-cyclic-overview-labels-and-flow-rules.md` (29606 bytes) - `docs/Technical-Reference/WikiData-Orgo_Chart.md` (6970 bytes) - `LICENSE` (688 bytes) - `package-scripts.js` (1998 bytes) - `package.json` (681 bytes) - `packages/config/eslint-preset.js` (240 bytes) - `packages/config/nginx.conf` (1491 bytes) - `packages/config/package.json` (281 bytes) - `packages/config/postcss.config.js` (89 bytes) - `packages/config/tailwind.config.js` (221 bytes) - `packages/tsconfig/base.json` (541 bytes) - `packages/tsconfig/nestjs.json` (604 bytes) - `packages/tsconfig/nextjs.json` (590 bytes) - `packages/tsconfig/package.json` (178 bytes) - `packages/tsconfig/react-library.json` (245 bytes) - `packages/tsconfig/README.md` (109 bytes) - `packages/ui/components/Button/Button.tsx` (98 bytes) - `packages/ui/index.tsx` (45 bytes) - `packages/ui/package.json` (479 bytes) - `packages/ui/tsconfig.json` (120 bytes) - `README.md` (7111 bytes) - `turbo.json` (455 bytes) ================================================================================================ FILE: Docs/README.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: cde22c1b878242baf6d6111bc50491319a6d90e1dc3101d6b330c5c4e7f48208 CONTENT_BYTES: 4316 ================================================================================================ > Current delivery: [Implementation status](Technical-Reference/IMPLEMENTATION_STATUS.md), [adopted decisions](Technical-Reference/IMPLEMENTATION_DECISIONS.md), [implemented API](Technical-Reference/API_IMPLEMENTED.md). # Orgo — Documentation ## Scope Orgo is a **proprietary integrated subsystem/application** in the kOA Digital Ecosystem. It is a multi-tenant workflow and coordination system that turns signals into governed operational work through Organizations, Cases, Tasks, labels, profiles, workflows, audit and insights. Its target implementation style is a modular monolith centered on Intake, Work and Orchestration. Orgo owns **workflow state, business authorization and its business UI**. It can run standalone. When hosted by Koali Spaces it is contributed as a `local_module_surface`; Koali hosts/composes Orgo but does not become the owner of Orgo's Tasks, Cases, Signals, Workflows, tenant rules, RBAC or UI. Orgo does not absorb the business state of Konnaxion, the epistemic state of Kristal, the linguistic runtime of SemantiK Architect, or the host/platform state of kOA-Linux. ## Canonical reading order 1. `Technical-Reference/TARGET_ARCHITECTURE.md` — canonical target architecture and migration strategy. 2. `Technical-Reference/v3/1-Orgo v3 - Database Schema Reference.md` — current physical schema reference. 3. `Technical-Reference/v3/2-Orgo v3 - Architecture and Invariants.md` 4. `Technical-Reference/v3/3-Orgo v3 - Task Case and Workflow Contract.md` 5. `Technical-Reference/v3/4-Orgo v3 - Domain Modules.md` 6. `Technical-Reference/v3/5-Orgo v3 - Labels Profiles and Cyclic Overview.md` 7. `Technical-Reference/v3/6-Orgo v3 - Insights and Analytics.md` 8. `Technical-Reference/v3/7-Orgo v3 - API Surface.md` 9. `Technical-Reference/UI_AND_KOALI_INTEGRATION.md` 10. `Technical-Reference/BOUNDARIES_AND_OWNERSHIP.md` 11. `Technical-Reference/GLOSSARY.md` 12. `Technical-Reference/CODE_ALIGNMENT_NOTES.md` ## Core invariants - `Organization` is the tenant boundary. - `Work` is the central operational bounded context; it owns canonical Case/Task mutations. - `Task` is the canonical executable unit of work. - `Case` is the durable situation/context and primary operational workspace. - `Signal` is a first-class accepted input/evidence object in the target architecture; the current schema still requires this persistence model to be added. - Domain modules refine the Task/Case engine; they do not create competing core lifecycles. - Canonical labels drive routing/classification but do not replace domain state. - Broadcast labels are informational by default unless an explicit workflow creates work. - Workflow evaluation is deterministic and side-effect free; an Action Executor applies resolved actions through owner services. - Durable external/long-running effects use idempotency, an outbox/worker boundary and explicit receipts. - Insights are read/analysis projections; actionable patterns re-enter Work as Cases/Tasks. - External systems are orchestrated through explicit contracts; Orgo does not write their internal stores. - Workflow state is not epistemic, civic, linguistic or platform state. - Orgo remains standalone-capable; Koali hosting is an integration mode, not a required business dependency. - Koali capability projections may influence presentation but never replace Orgo authorization. - Orgo presentation profiles compose shared UI capabilities; reduced surfaces are not implemented by cloning or merely hiding a monolithic Control Panel. ## Current code reference The supplied code snapshot contains the real Prisma schema, migrations, NestJS services/controllers, domain modules, charters and web application. The physical schema and executable code are the implementation reference; this documentation defines the aligned architecture those surfaces should implement. ## Completion delivery reference — 2026-09-09 The active implementation and its remaining external-contract boundaries are recorded in `IMPLEMENTATION_STATUS.md`. See `COMPLETION_DECISIONS.md` for durable processes, receipt predicates, Work scopes, identity and evidence semantics; `ARCHITECTURE_TO_CODE.md` for source ownership; `LOCAL_VALIDATION.md` for the final acceptance to run locally. Historical validation results do not validate the completion changes. ================================================================================================ FILE: Docs/status/2026-09-10-beta-status.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 5b6cf02af37f3ead67ae17b025754834afe977721c6c97ed884dca3f687044a5 CONTENT_BYTES: 4381 ================================================================================================ # Orgo — Rapport de statut du 10 septembre 2026 ## Décision : bêta Le niveau recommandé est **bêta**, pas encore release candidate (RC). Les campagnes `deep` et `browser` ont réussi selon les résultats communiqués dans la conversation. Ces résultats permettent de poursuivre les essais fonctionnels ; ils ne démontrent pas encore la complétude du périmètre de livraison. Ce rapport est établi à partir des résultats transmis, sans nouvelle exécution ni inspection du dépôt. Le commit testé, la branche et les tags existants restent à identifier. Aucun tag n’a été créé ou poussé dans le cadre de ce rapport. ## Éléments de validation disponibles | Campagne | Résultat communiqué | Périmètre | | --- | --- | --- | | `deep` | PASS — 12 niveaux sur 12 | Intégrité du diagnostic, contexte et inventaire du dépôt, hygiène, outils, sécurité, preflight Orgo, schéma/architecture/types, tests métier, intégration PostgreSQL native, builds API/web, audit des dépendances au seuil moderate+ | | `browser` / N15 | PASS — 7 tests réussis, 0 échec, 0 ignoré | Parcours Playwright avec la vraie API et PostgreSQL | Référence de la campagne `deep` : `20260910T015821Z-e0b2ce01`. Rapport local communiqué : `C:\mycode\Orgo\LevelUpDiag-Orgo\.levelupdiag\runs\20260910T015821Z-e0b2ce01\summary.json`. La référence précise du rapport final `browser` et les SHA Git associés ne sont pas disponibles dans le contexte fourni. Le succès de N15 provient du compte rendu de lecture du rapport dans la conversation. Les sept scénarios navigateur couvrent : 1. Le refus d’identifiants invalides. 2. La connexion, la recherche clavier et la déconnexion. 3. La création, la recherche et la réouverture d’un dossier. 4. La création, la recherche et la réouverture d’une tâche. 5. La création, la recherche et la réouverture d’un signal. 6. Les transitions d’une tâche. 7. Une recherche sans résultat. ## Incidents résolus pendant la validation - PostgreSQL indisponible : après remise en disponibilité, les campagnes `database` puis `deep` ont passé. - Sélecteur d’alerte Playwright ambigu avec l’annonceur Next.js : correction du test. - Détection de disponibilité du lanceur : lecture corrigée de `data.status` dans la réponse de l’API. - Connexion HTTP 401 : mot de passe du compte de test non concordant ; le succès final des sept scénarios confirme que le blocage de connexion est levé. La console LevelUpDiag a reçu des paramètres navigateur et des commandes de démarrage/arrêt de la pile de test. Ces changements appartiennent à l’outil de diagnostic séparé ; leur présence dans une version d’Orgo ne doit pas être supposée. ## Conditions proposées pour une RC - Définir le périmètre fonctionnel de la version et vérifier chaque fonctionnalité attendue par rapport à la documentation. - Compléter la validation des permissions et de l’isolation entre organisations, des pièces jointes, des workflows et des autres parcours retenus pour la livraison. - Établir la liste des anomalies connues et confirmer l’absence de défaut bloquant dans ce périmètre. - Vérifier l’installation et les migrations dans un environnement représentatif de la livraison. - Rattacher les rapports `deep` et `browser` au même état de code destiné au tag ; relancer les contrôles concernés si le code ou ses dépendances ont changé. Ces points sont des validations restant à documenter, pas des défauts constatés. ## Préparation du tag GitHub Utiliser un tag de préversion bêta conforme aux conventions du dépôt. **`v0.1.0-beta.1` est une proposition conditionnelle**, à retenir uniquement si la prochaine version visée est bien `0.1.0` et si ce tag n’existe pas déjà. Les mentions `api@0.1.0` et `web@0.1.0` dans les journaux ne suffisent pas à établir la version de livraison. Avant le push : identifier le dépôt, sa branche de livraison, les versions et tags existants ; intégrer ce rapport dans `docs/status` ; vérifier les modifications locales et le commit à publier ; rattacher les preuves de tests à cet état. Créer ensuite un tag annoté sur le commit retenu et pousser uniquement ce tag. Ne pas remplacer un tag existant. Si une GitHub Release est créée, la marquer comme préversion et reprendre les limites de couverture ci-dessus. ================================================================================================ FILE: Docs/Technical-Reference/API_IMPLEMENTED.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: d210e31589cc6f69f31c1b396322c6ec8cf33885c4f4aa53a8a58bc593169121 CONTENT_BYTES: 8057 ================================================================================================ # Orgo — Implemented HTTP routes Generated from active controllers for the completion delivery, 2026-09-09. Route implementation is distinct from final runtime acceptance; see `LOCAL_VALIDATION.md`. Health, login/recovery/reset and OIDC initiation/completion are explicitly public. Other routes require authentication. Product mutations generally require `Idempotency-Key`; password/login/SSO have their own security lifecycle. Tenant identity always comes from authentication. CSV and metrics routes return their declared content type; other routes use the Orgo JSON envelope. | Method | Route | Owner file | | --- | --- | --- | | GET | `/api/v3/organizations` | `admin.controller.ts` | | GET | `/api/v3/people` | `admin.controller.ts` | | POST | `/api/v3/people` | `admin.controller.ts` | | GET | `/api/v3/users` | `admin.controller.ts` | | POST | `/api/v3/users` | `admin.controller.ts` | | GET | `/api/v3/roles` | `admin.controller.ts` | | POST | `/api/v3/roles` | `admin.controller.ts` | | PUT | `/api/v3/users/:id/roles` | `admin.controller.ts` | | GET | `/api/v3/config/profile` | `admin.controller.ts` | | PUT | `/api/v3/config/profile` | `admin.controller.ts` | | GET | `/api/v3/maintenance/assets` | `admin.controller.ts` | | POST | `/api/v3/maintenance/assets` | `admin.controller.ts` | | POST | `/api/v3/maintenance/tasks` | `admin.controller.ts` | | POST | `/api/v3/hr/cases` | `admin.controller.ts` | | GET | `/api/v3/education/groups` | `admin.controller.ts` | | POST | `/api/v3/education/groups` | `admin.controller.ts` | | POST | `/api/v3/education/tasks` | `admin.controller.ts` | | POST | `/api/v3/auth/login` | `auth.controller.ts` | | GET | `/api/v3/auth/me` | `auth.controller.ts` | | POST | `/api/v3/auth/logout` | `auth.controller.ts` | | GET | `/api/v3/work/:type/:id/attachments` | `completion.controller.ts` | | POST | `/api/v3/work/:type/:id/attachments` | `completion.controller.ts` | | GET | `/api/v3/attachments/:id` | `completion.controller.ts` | | DELETE | `/api/v3/attachments/:id` | `completion.controller.ts` | | GET | `/api/v3/work/:type/:id/timeline` | `completion.controller.ts` | | GET | `/api/v3/work/:type/:id/relations` | `completion.controller.ts` | | POST | `/api/v3/work/:type/:id/relations` | `completion.controller.ts` | | POST | `/api/v3/processes` | `completion.controller.ts` | | GET | `/api/v3/processes` | `completion.controller.ts` | | GET | `/api/v3/processes/:id` | `completion.controller.ts` | | POST | `/api/v3/processes/:id/decision` | `completion.controller.ts` | | POST | `/api/v3/processes/:id/adopt` | `completion.controller.ts` | | POST | `/api/v3/processes/:id/compensate` | `completion.controller.ts` | | POST | `/api/v3/integration-operations/:id/receipt` | `completion.controller.ts` | | GET | `/api/v3/identity/tokens` | `completion.controller.ts` | | POST | `/api/v3/identity/tokens` | `completion.controller.ts` | | DELETE | `/api/v3/identity/tokens/:id` | `completion.controller.ts` | | POST | `/api/v3/identity/users/:id/invite` | `completion.controller.ts` | | PUT | `/api/v3/identity/users/:id/status` | `completion.controller.ts` | | POST | `/api/v3/auth/password` | `completion.controller.ts` | | POST | `/api/v3/auth/recover` | `completion.controller.ts` | | POST | `/api/v3/auth/reset` | `completion.controller.ts` | | GET | `/api/v3/maintenance/calendar` | `completion.controller.ts` | | POST | `/api/v3/maintenance/calendar` | `completion.controller.ts` | | PUT | `/api/v3/maintenance/calendar/:id/status` | `completion.controller.ts` | | GET | `/api/v3/hr/cases` | `completion.controller.ts` | | GET | `/api/v3/hr/cases/:id` | `completion.controller.ts` | | POST | `/api/v3/hr/cases/:id/participants` | `completion.controller.ts` | | PUT | `/api/v3/hr/cases/:id/review` | `completion.controller.ts` | | POST | `/api/v3/hr/wellbeing` | `completion.controller.ts` | | GET | `/api/v3/education/groups/:id/members` | `completion.controller.ts` | | POST | `/api/v3/education/groups/:id/members` | `completion.controller.ts` | | DELETE | `/api/v3/education/members/:id` | `completion.controller.ts` | | GET | `/api/v3/identity/users/:id/scopes` | `completion.controller.ts` | | POST | `/api/v3/identity/users/:id/scopes` | `completion.controller.ts` | | DELETE | `/api/v3/identity/scopes/:id` | `completion.controller.ts` | | POST | `/api/v3/identity/invitations` | `completion.controller.ts` | | GET | `/health/live` | `health.controller.ts` | | GET | `/health/ready` | `health.controller.ts` | | GET | `/health/dependencies` | `health.controller.ts` | | POST | `/api/v3/ingress/email` | `ingress.controller.ts` | | GET | `/api/v3/ingress/email/:signalId` | `ingress.controller.ts` | | GET | `/api/v3/ingress/email/:signalId/attachments/:index` | `ingress.controller.ts` | | POST | `/api/v3/ingress/webhook` | `ingress.controller.ts` | | POST | `/api/v3/integration-operations` | `operations.controller.ts` | | GET | `/api/v3/integration-operations/:id` | `operations.controller.ts` | | GET | `/api/v3/integration-operations` | `operations.controller.ts` | | GET | `/api/v3/notifications` | `operations.controller.ts` | | POST | `/api/v3/notifications` | `operations.controller.ts` | | GET | `/api/v3/outbox` | `operations.controller.ts` | | POST | `/api/v3/outbox/:id/redrive` | `operations.controller.ts` | | GET | `/api/v3/insights/overview` | `operations.controller.ts` | | GET | `/api/v3/audit` | `operations.controller.ts` | | GET | `/api/v3/signals` | `process.controller.ts` | | GET | `/api/v3/signals/:id` | `process.controller.ts` | | POST | `/api/v3/signals` | `process.controller.ts` | | POST | `/api/v3/signals/:id/process` | `process.controller.ts` | | GET | `/api/v3/workflows` | `process.controller.ts` | | POST | `/api/v3/workflows/:code/versions` | `process.controller.ts` | | POST | `/api/v3/workflows/:code/import` | `process.controller.ts` | | GET | `/api/v3/workflow-versions/:id/export` | `process.controller.ts` | | POST | `/api/v3/workflow-versions/:id/simulate` | `process.controller.ts` | | POST | `/api/v3/workflow-versions/:id/execute` | `process.controller.ts` | | GET | `/api/v3/communications/templates` | `product-operations.controller.ts` | | PUT | `/api/v3/communications/templates/:code` | `product-operations.controller.ts` | | POST | `/api/v3/communications/templates/:code/send` | `product-operations.controller.ts` | | PUT | `/api/v3/notifications/:id/read` | `product-operations.controller.ts` | | GET | `/api/v3/reports/tasks.csv` | `product-operations.controller.ts` | | GET | `/api/v3/system/overview` | `product-operations.controller.ts` | | GET | `/api/v3/system/metrics` | `product-operations.controller.ts` | | POST | `/api/v3/system/retention` | `product-operations.controller.ts` | | GET | `/api/v3/routing/rules` | `routing.controller.ts` | | POST | `/api/v3/routing/rules` | `routing.controller.ts` | | POST | `/api/v3/routing/tasks/:id` | `routing.controller.ts` | | GET | `/api/v3/auth/sso/config` | `sso.controller.ts` | | POST | `/api/v3/auth/sso/start` | `sso.controller.ts` | | POST | `/api/v3/auth/sso/complete` | `sso.controller.ts` | | GET | `/api/v3/identity/sso` | `sso.controller.ts` | | POST | `/api/v3/identity/sso` | `sso.controller.ts` | | DELETE | `/api/v3/identity/sso/:id` | `sso.controller.ts` | | POST | `/api/v3/sync/replay` | `sync.controller.ts` | | GET | `/api/v3/tasks` | `work.controller.ts` | | GET | `/api/v3/tasks/:id` | `work.controller.ts` | | POST | `/api/v3/tasks` | `work.controller.ts` | | PATCH | `/api/v3/tasks/:id/status` | `work.controller.ts` | | PATCH | `/api/v3/tasks/:id/assignment` | `work.controller.ts` | | PATCH | `/api/v3/tasks/:id` | `work.controller.ts` | | POST | `/api/v3/tasks/:id/comments` | `work.controller.ts` | | GET | `/api/v3/cases` | `work.controller.ts` | | GET | `/api/v3/cases/:id` | `work.controller.ts` | | POST | `/api/v3/cases` | `work.controller.ts` | | PATCH | `/api/v3/cases/:id/status` | `work.controller.ts` | | PATCH | `/api/v3/cases/:id` | `work.controller.ts` | | PATCH | `/api/v3/tasks/:id/case` | `work.controller.ts` | Total: **114 routes**. ================================================================================================ FILE: Docs/Technical-Reference/ARCHITECTURE_TO_CODE.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 0c1a272d26262c0ccab0b8eaadc34347c0ec7bb48db9aecc0a39bd54b408f67a CONTENT_BYTES: 4304 ================================================================================================ # Target architecture → active code → local acceptance Paths are relative to `apps/api/src/orgo/` unless otherwise specified. This is an architecture coverage map, not a claim of exhaustive acceptance for every historical draft. | Requirement | Active implementation | UI/API entry | Local verification | | --- | --- | --- | --- | | Transactional core / Work owner | `modules/work/work.service.ts`, `platform/database.ts` | Cases, Tasks | Tenant, revision, lifecycle tests | | Persist Signal before effects | `modules/intake/intake.service.ts` | Signals, ingress | Durable acceptance / rollback tests | | Pure evaluator | `modules/orchestration/evaluator.ts` | Workflow simulation | Pure unit tests, architecture rule | | Frozen runtime versions | `modules/orchestration/workflow.service.ts` | Workflow versions | Version pinning / immutable SQL trigger | | Internal and external action split | `modules/orchestration/actions.ts` | Workflow execution | Transaction rollback / queued operation tests | | Durable process managers | `modules/orchestration/process-manager.service.ts` | Processes; `START_PROCESS` | Human revision / async callback tests; timers/restarts locally | | External ACLs | `integrations/*`, `modules/integrations/operations.service.ts` | Operations / receipts | Bridge tests; native provider contracts still required | | Tenant + actor context | `platform/contracts.ts`, `modules/identity/*` | Auth boundary | Spoofed tenant and revoked actor tests | | Scoped Work authorization | `WorkService` filters/assertions; `IdentityService.workGrants` | Access / Work scope fields | Team alpha/beta regression test | | Idempotency | `platform/database.ts` | Mutation keys / offline command IDs | Repeated/concurrent commands, conflicts | | Outbox reliability | `platform/outbox/worker.service.ts` | System / redrive | Lease fencing, native skip-locked test | | Signal/email evidence | HTTP ingress + `scripts/email-ingress.py` | Signal inspector | Attachment isolation test; IMAP/mbox fixture runs locally | | Work evidence/history | `modules/work/evidence.service.ts` | Work inspector | Upload/replay/tenant/tombstone tests | | Operational relationships | `WorkService.linkCase`, `EvidenceService.relate` | Work editor / relations | Scope, visibility and revision checks locally | | Routing and SLA | `modules/orchestration/routing.service.ts`, `escalation.service.ts` | Routing / worker | Routing / canonical escalation tests | | Identity administration | `modules/identity/identity-admin.service.ts` | Access, account page | Token/recovery/revocation acceptance locally | | Optional SSO | `modules/identity/oidc.service.ts` | Login / subject enrollment | Provider + negative JWT/state/nonce cases locally | | Notifications/templates | `modules/communications/*` | Messages / notifications | In-app and template tests; SMTP/gateway locally | | Maintenance | `modules/domains/domain-management.service.ts`, `domains.service.ts` | Maintenance | Task-link and overlap tests | | HR | Same domain owner services | HR | Atomic creation tests; review/participants locally | | Education | Same domain owner services | Education | Extension tests; membership lifecycle locally | | Read queries and export | `modules/insights/*`, operations HTTP controller | Insights, Reports | Visibility tests; CSV boundary/browser locally | | Offline resilience | `apps/web/src/orgo/offline.ts`, HTTP sync | Offline | Replay tests; browser disconnect/conflicts locally | | Optional hosted composition | `apps/web/src/orgo/hosted-entry.tsx`, `public-contract.ts` | Shared Orgo app | Real host + CSS/bundling/admission when contracts supplied | | Observability | `platform/telemetry.ts`, worker heartbeat, system endpoints | System / metrics | Collector/failure/load acceptance locally | | Lifecycle / preservation | SQL migrations, retention endpoint, operations scripts | Admin commands / deployment | Native migrations + backup/restore locally | | Packaging / enforcement | RuntimeModule, package scripts, Dockerfiles, CI | Same-release API/worker/web | `validate:local`, Compose and browser locally | `API_IMPLEMENTED.md` inventories routes. `COMPLETION_DECISIONS.md` defines process, scope, account, bridge and evidence semantics. `LOCAL_VALIDATION.md` is the owner's executable acceptance procedure. ================================================================================================ FILE: Docs/Technical-Reference/Boilerplate_Turborepo.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: adbb8be266bc9663242de812e2cd4f878f9d5011c3b52c5bd8c760d2fa026899 CONTENT_BYTES: 2263 ================================================================================================ # Turborepo (NestJS + Prisma + NextJS + Tailwind + Typescript + Jest) Starter This is fullstack turborepo starter. It comes with the following features. - ✅ Turborepo - ✅ Nestjs - ✅ Env Config with Validation - ✅ Prisma - ✅ NextJS - ✅ Tailwind - ✅ Redux Toolkit Query - ✅ Testing using Jest - ✅ Github Actions - ✅ Reverse Proxy using Nginx - ✅ Docker Integration - ✅ Postgres Database - ✅ Package scripts using NPS ## What's inside? This turborepo uses [Yarn](https://classic.yarnpkg.com/lang/en/) as a package manager. It includes the following packages/apps: ### Apps and Packages - `api`: a [NestJS](https://nestjs.com/) app - `web`: a [Next.js](https://nextjs.org) app - `ui`: a stub React component library used by `web`. - `config`: `eslint`, `nginx` and `tailwind` (includes `eslint-config-next` and `eslint-config-prettier`) - `tsconfig`: `tsconfig.json`s used throughout the monorepo Each package/app is 100% [TypeScript](https://www.typescriptlang.org/). ### Utilities This turborepo has some additional tools already setup for you: - [Node Package Scripts](https://github.com/sezna/nps#readme) for automation scripts - [TypeScript](https://www.typescriptlang.org/) for static type checking - [ESLint](https://eslint.org/) for code linting - [Prettier](https://prettier.io) for code formatting ## Setup This starter kit is using turborepo and yarn workspaces for monorepo workflow. ### Prerequisites - Install nps by running ``` npm i -g nps ``` - Make sure docker and docker-compose are installed. Refer to docs for your operating system. ### Configure Environment - Frontend - `cd apps/web && cp .env.example .env` - Backend - `cd apps/api && cp .env.example .env` ### Install Dependencies Make sure you are at root of the project and just run ``` nps prepare ``` ### Build To build all apps and packages, run the following command at the root of project: ``` nps build ``` ### Develop To develop all apps and packages, run the following command at the root of project: ``` nps dev ``` The app should be running at `http://localhost` with reverse proxy configured. ## Other available commands Run `nps` in the terminal to see list of all available commands. ================================================================================================ FILE: Docs/Technical-Reference/BOUNDARIES_AND_OWNERSHIP.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: c4205b4cd0f877ee5e731532564340460e2dbc62ca46e63a433176dcef348a0e CONTENT_BYTES: 5598 ================================================================================================ # Orgo — Boundaries and Ownership ## 1. Orgo owns operational workflow state Orgo owns: - organizations and organization profiles; - Orgo user/person/RBAC state; - accepted/persisted Signals (target architecture; model not yet present in current Prisma snapshot); - Cases; - Tasks; - assignments/comments/events; - labels/routing rules; - workflow definitions/executions/transitions within Orgo; - escalation/SLA state; - notifications/audit/security events in the Orgo scope; - offline/sync state in the Orgo scope; - domain-extension records that are explicitly part of Orgo; - insights/read models derived from Orgo operational state. ## 2. Work / Task / Case ownership `Work` is the central operational bounded context. `Task` is the canonical executable unit of work. `Case` is the shared durable situation/context container. `Work` owns canonical Case/Task mutations, assignments/comments and work events. It is an ownership boundary, not a replacement database object. Domain modules must not create a second competing Task/Case lifecycle. Domain tables may extend a Task/Case through explicit foreign keys/links. Examples already present in the physical schema: - `maintenance_task_links` → canonical Task; - `hr_cases` → canonical Case; - `hr_case_task_links` → canonical Task; - `education_task_links` → canonical Task. ## 3. Insights ownership Insights owns analytical projections and reporting outputs. It does not own operational Tasks/Cases. When a pattern requires action: ```text insight/pattern → explicit core Case/Task creation → normal Orgo lifecycle ``` ## 4. Orgo ↔ Konnaxion There is no implemented Konnaxion adapter in the current Orgo snapshot. No implicit identity is allowed: ```text Orgo Case ≠ Konnaxion Topic Orgo Task ≠ Konnaxion Consultation Orgo label ≠ Konnaxion taxonomy Orgo workflow status ≠ civic decision status ``` Future interaction pattern: ```text Orgo workflow → command/job/proposal/artifact ref → Konnaxion validates/authorizes → Konnaxion mutates its own state → receipt/event/result → Orgo reconciles its Task/Case ``` If Konnaxion requests governed work, Orgo creates/updates its own Tasks/Cases; Konnaxion does not write the Orgo database. ## 5. Orgo ↔ Kristal There is no implemented Kristal adapter in the current Orgo snapshot. Orgo may eventually orchestrate Kristal operations and keep artifact references/receipts, but: ```text Task.status ≠ Kristal assertion_status Case.status ≠ Kristal validation_status Orgo approval ≠ Kristal validation Orgo approval ≠ Kristal authority recognition ``` A workflow approval becomes a Kristal epistemic decision only through an explicit Kristal operation/artifact. ## 6. Orgo ↔ SemantiK Architect No SemantiK Architect adapter is implemented in the current Orgo snapshot. A future boundary should pass semantic generation requests/results without making Architect the owner of Orgo Tasks/Cases and without encoding Architect internal planner objects in the Orgo core. ## 7. Orgo ↔ Koali Spaces Orgo is an owner-managed subsystem/application. It can run standalone. When installed in Koali Spaces, it is exposed as a `local_module_surface` through the canonical module/interface manifest mechanism. Koali owns: - the `GlobalShell`; - Space composition; - module selection and outer navigation; - module hosting; - capability projection used for presentation. Orgo retains ownership of: - Cases, Tasks, Signals, Workflows and Routing; - tenant/business rules and Orgo RBAC; - Orgo routes and inner navigation; - the Orgo Control Panel, Inspector, commands and presentation profiles. Capability snapshots/projections are non-authoritative. Koali may use them to show/hide/enable/disable UI or choose a safe route, but Orgo must revalidate identity, tenant, RBAC and policy before every protected mutation. Do not assume that a Koali session is automatically an authorized Orgo session unless an explicit SSO/identity contract establishes that mapping. Do not create a second global Koali shell inside Orgo. Koali outer navigation and Orgo inner navigation intentionally coexist. ## 8. Orgo ↔ kOA-Linux When Orgo is hosted/integrated by kOA-Linux: - Orgo keeps Task/Case/workflow/domain authority; - kOA-Linux owns host resources, trust, privilege mediation, local service lifecycle, artifact admission/activation and recovery in its platform scope. Host/platform state must not be represented as ordinary Orgo business state unless a real use case requires an Orgo Task to track that operation. ## 9. Durable effects and integration ownership Orgo distinguishes the decision to perform an effect from the execution of a remote/long-running effect. ```text owner business transaction + OutboxMessage → commit → Orgo worker → adapter → receipt/result ``` `OutboxMessage` is delivery infrastructure. `IntegrationOperation` is Orgo-owned operational state for a request to an external system. Neither replaces the external system's authoritative state. External operation status must not be folded into Task/Case lifecycle by implication. ## 10. Integration boundary rule Use one explicit port/adapter/Anti-Corruption Layer per independently owned external system. External provider/domain types stop at that boundary. The boundary should carry only what is needed: - external object/artifact reference; - intended operation; - organization/tenant mapping when required; - actor/authorization context; - correlation/causation/idempotency identity; - result/error/receipt; - provenance/audit references. ================================================================================================ FILE: Docs/Technical-Reference/CODE_ALIGNMENT_NOTES.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 19e1f2ab22b3857288043d92d0496c169eb673f4c1f5031d04ca324e4040071e CONTENT_BYTES: 19550 ================================================================================================ # Orgo — Code Alignment Notes > **Implementation update (2026-09-09):** The detailed findings below describe the supplied pre-migration snapshot, now retained under `legacy/`. They are not a list of defects claimed to remain in the new active runtime. See `IMPLEMENTATION_STATUS.md`, `IMPLEMENTATION_DECISIONS.md` and `API_IMPLEMENTED.md` for current delivery evidence. ## Purpose This note identifies code areas that should be changed so the implementation matches the current Orgo architecture. It is not a project-management log. The canonical target is `TARGET_ARCHITECTURE.md`. Migration is incremental: repair the existing snapshot first, then establish module boundaries and introduce new durable primitives without a rewrite. ## 1. Repair the Nest module/import graph first The snapshot contains several imports that do not resolve to files in the supplied tree. These block reliable execution before higher-level alignment can be trusted. ### `apps/api/src/orgo/core/tasks/task.service.ts` Current imports use paths shaped like: ```text ./././persistence/prisma/prisma.service ./././config/org-profile.service ``` They do not resolve from `core/tasks`. Wire them to the actual shared persistence/config services. ### `apps/api/src/orgo/core/cases/case.module.ts` Imports `case-review.service` and `../database/database.module`, neither of which is present in the supplied tree. The actual CaseService already uses Prisma persistence. Rebuild CaseModule around the real persistence/core dependencies instead of phantom modules. ### `apps/api/src/orgo/core/logging/logger.module.ts` References `log-rotation.service` and `log-query.service`, which are absent in the snapshot. Either add the real implementations or remove them from the active module contract. ### `apps/api/src/orgo/config/org-profile.service.ts` Contains a malformed relative persistence import. Point it to the actual `apps/api/src/persistence/prisma/prisma.service.ts`. ## 2. Fix the public Task boundary mapping and tenant enforcement ### `apps/api/src/orgo/core/tasks/task.controller.ts` The public DTO is snake_case (`organization_id`, `case_id`, etc.) while `TaskService` expects camelCase (`organizationId`, `caseId`, etc.). The controller currently passes objects through with `as any`. Consequences include: - list input may not populate `organizationId`; - create input may fail core validation or map fields incorrectly; - response shape can leak internal camelCase instead of the documented public shape. Add explicit request/response mappers. ### Tenant isolation `getTask()` currently calls an unscoped service lookup by Task ID. List/create also rely on DTO input rather than one consistent authenticated organization context. Change Task HTTP paths to: ```text resolve authenticated organization → map public DTO to internal input → call org-scoped service method → map internal DTO to public JSON ``` Use `getTaskById(organizationId, taskId)` for public single-task access. ## 3. Make Case API/service responsibilities explicit `CaseService` implements `createCaseFromSignal()` and `updateCaseStatus()`, but `CaseController` exposes only list/detail in the snapshot. Choose one stable contract: - if Case create/status are intended public APIs, expose validated endpoints; - if they are internal workflow operations, keep them internal and document only list/detail publicly. Do not claim an endpoint exists just because a service method exists. ## 4. Unify API route prefixing `main.ts` defines no global API prefix, while controllers mix: ```text api/v3/tasks api/v3/workflows api/v3/organizations v3/cases signals notifications maintenance domain/hr domain/education insights/reports ``` Select one public routing convention, ideally a single `/api/v3` boundary for Orgo APIs, and make reverse-proxy behavior explicit rather than relying on comments. ## 5. Update bootstrap identity ### `apps/api/src/main.ts` Swagger currently identifies the API as: ```text Leaves Tracker Api Docs for leaves tracker version 1.0 ``` Replace with Orgo identity/version metadata and make the port/config environment-driven rather than hard-coded where appropriate. ## 6. Wire the core modules that exist in source The current `AppModule`/`OrgoModule` wiring does not expose all implemented core areas. Source contains Email, Signals, Notifications, Auth/RBAC, Offline and other modules, but several are not imported into the active module graph. Examples: - `SignalsModule` is not imported and currently declares no imports despite `SignalIngestService` requiring WorkflowEngineService and TaskService; - `EmailModule` exists but is not mounted by AppModule/OrgoModule, and its controller is not registered in the module; - `NotificationController` exists but `NotificationModule` does not register it as a controller; - Auth/RBAC code exists but AppModule does not establish one consistent authenticated tenant context for the core APIs. Wire only the capabilities intended to be active, but make the module graph truthful. ## 7. Preserve WorkflowEngine purity and add an explicit action executor `WorkflowEngineService` is already architecturally strong: it loads/validates rules and resolves ordered actions without performing all side effects itself. Preserve that separation. Current `SignalIngestService` applies `CREATE_TASK` actions, but the rule vocabulary also includes UPDATE_TASK, ROUTE, ESCALATE, ATTACH_TEMPLATE, SET_METADATA and NOTIFY. The docs also expect workflows/patterns to be able to open Cases. Add a clear executor/dispatcher layer: ```text resolved action → action executor ├── internal action -> Work/owner service -> ACID transaction └── external/long action -> OutboxMessage -> worker -> adapter -> receipt ``` Do not put persistence side effects back into the pure evaluator and do not synchronously couple a Work transaction to a remote integration. ## 8. Reconcile filesystem workflow rules with DB workflow models Prisma contains: ```text WorkflowDefinition WorkflowInstance WorkflowTransitionEvent ``` while the active Workflow Engine loads rules from the filesystem/YAML. Converge on the target relationship: ```text WorkflowDefinition → immutable WorkflowVersion → WorkflowInstance pins exact version/hash ``` Use YAML/filesystem definitions for authoring/import/export/seed/test fixtures. Do not keep them as an unrelated mutable runtime source of truth. ## 9. Fix Maintenance before treating it as an active domain module ### `apps/api/src/orgo/domain/maintenance/maintenance.module.ts` The file is not a Nest `@Module`; it contains another `MaintenanceController`, duplicating `maintenance.controller.ts` with a different API/authorization shape. ### `maintenance.service.ts` The service creates its own `PrismaClient` and performs raw Task-table operations/transactions directly. Align Maintenance to: ```text MaintenanceModule → one controller → MaintenanceService → TaskService for canonical Task mutations → MaintenanceAsset/MaintenanceTaskLink/MaintenanceCalendarSlot for domain extension ``` The module should then be explicitly imported if Maintenance is intended active. ## 10. Fix Education to use the core work owner ### `education.module.ts` / `education.controller.ts` They import `education-module.service`, while the supplied file is `education.service.ts`. ### `education.service.ts` It has a malformed persistence import and directly writes/queries canonical Task rows through raw SQL. Refactor creation/status mutations through TaskService. Keep `EducationTaskLink`, LearningGroup and person context as Education-owned extensions. ## 11. Fix HR integration with TaskService/CaseService HR has the correct architectural intention — create a canonical Case, create a canonical Task, then add `HrCase`/participants/links — but the current code does not match the core service APIs. Issues include: - imports from nonexistent `core/task`, `core/case`, `core/label` paths; - `CaseService.createCase(...)` is called but the supplied CaseService exposes `createCaseFromSignal(...)`; - TaskService/CaseService are called with a transaction client argument their current signatures do not accept. Align the service APIs and transaction boundary so the canonical Task/Case plus HR extension commit consistently. Remove `hr.service.ts.BAK` from the active source tree. ## 12. Consolidate Insights layout/imports `InsightsModule` imports root-level files such as: ```text ./reports.controller ./reports.service ./analytics-export.service ``` while the supplied tree also places implementations under subfolders such as: ```text insights/reports/ insights/export/ insights/patterns/ insights/cache/ ``` There are duplicate root/subfolder pattern/cache implementations in the snapshot. Choose one canonical folder layout, update imports, and keep Insights read-oriented. Pattern actions should re-enter the core through TaskService/CaseService. ## 13. Keep enums/contracts in one semantic source Task/Case/visibility/category enums are repeated in controllers, services, web types and domain services. The values are mostly aligned now, which is good, but duplication creates drift risk. Prefer a shared contract package/generated API types or strict conversion layer so: - DB enum casing; - internal service casing; - public JSON casing; - web client types remain mechanically aligned. ## 14. Align offline sync with Task invariants `core/offline/sync.service.ts` writes Task rows directly during merge/sync. Offline operation is not exempt from core invariants. Ensure synchronized Task changes execute the same: - tenant checks; - enum/lifecycle rules; - ownership rules; - event/audit semantics; - conflict resolution evidence. If direct persistence is necessary for replay, isolate it behind a dedicated replay/import boundary with equivalent validation. ## 15. Build the frontend as an Orgo-owned application with composable presentation profiles The supplied web route tree currently has a root page that renders `InsightsOverviewPage`; it does not evidence a complete UI route set for Tasks, Cases, admin, HR, Education, etc. Keep current-state documentation truthful while implementing the target architecture. The target is one Orgo UI codebase with two entry modes: ```text Orgo UI ├── standalone entry └── Koali module entry -> local_module_surface ``` Do not create separate standalone and Koali page implementations. Internally, compose the UI from shared routes/components/actions/panels into Orgo presentation profiles (Full Control Panel, Operations, My Work, Supervisor, Intake, Workflow Admin, Executive, Embedded). A reduced profile must not be implemented merely by mounting the full Control Panel and hiding most of it. Treat `Case` as the primary operational workspace and Tasks/Signals as first-class transverse views. Add a contextual Orgo Inspector for quick context/actions, with deep links to full workspaces for complex work. Konnaxion may be reused selectively for layout mechanics, sidebar/header/drawer/page-shell patterns and ergonomics. Do not extract Konnaxion into a new global Koali shell; Koali already owns `GlobalShell`. Also verify `_app.tsx` style import and other web imports against files actually present in the repo. ## 16. External ecosystem adapters are not implemented No concrete Konnaxion, Kristal or SemantiK Architect adapter is present in the current snapshot. When added: ### Koali Spaces Integrate Orgo as a removable/standalone-capable owner-managed module surface. Use the canonical Module Interface Manifest and `local_module_surface` model. Preserve Orgo routing, state and business authorization. Koali capability projections may influence presentation only. Every protected mutation must be reauthorized by Orgo. Do not assume global SSO unless an explicit identity contract exists. Do not build a second `KoaliShell`. ### Konnaxion Use commands/events/receipts; never map Case↔Topic or Task↔Consultation by identity. ### Kristal Orchestrate explicit Kristal operations/artifact references. Orgo approval is not Kristal validation/recognition unless an explicit Kristal operation produces it. ### SemantiK Architect Use generation request/result contracts; do not store Architect internal planner objects as Orgo core models. ### kOA-Linux Treat host trust/resources/lifecycle as platform concerns. Track them in Orgo only when a real operational Task/Case is required. ## 17. Patterns that are already strong and should be preserved - Organization-scoped service methods in Task/Case core. - Explicit Task lifecycle transition table. - Explicit Case lifecycle transition table. - TaskEvent recording for important mutations. - `DomainTaskFactory` as a projection rather than a second Task table. - Label parser/routing service with explicit broadcast semantics. - Workflow evaluator separated from side effects. - Workflow simulation using the same evaluation semantics. - Profile-derived Task defaults. - Prisma schema linking domain extensions back to canonical Tasks/Cases. - Insights as a distinct read/analytics layer. ## 18. Refactor physical boundaries toward Intake / Work / Orchestration The current `Backbone / Core / Domain / Insights` tree is useful documentation but does not enforce ownership strongly enough in code. Migrate incrementally toward these logical boundaries: ```text Intake -> Signals and inbound normalization Work -> Cases + Tasks + assignments/comments/events Orchestration -> Workflow + routing + escalation + action dispatch ``` Do not perform a repository-wide rewrite. Move ownership/public APIs first, then relocate files only when it clarifies dependency direction. ## 19. Persist Signal as a first-class intake object The current snapshot contains Signal ingestion code but no canonical Prisma `Signal` model. Add an organization-scoped persisted Signal model with source/external reference/idempotency identity, normalized classification, payload/reference, processing status and timestamps. Target intake flow: ```text raw source → adapter/normalize → deduplicate/idempotency → persist Signal → orchestration evaluation → explicit Work actions ``` Link Signal to the Case/Tasks/actions it creates or enriches. Several Signals may relate to one Case. ## 20. Introduce one ExecutionContext boundary Controllers and adapters currently resolve organization/actor context inconsistently. Add a common application context carrying at least organization, actor, authorization reference, correlation/causation IDs, source and optional idempotency key. Resolve it once at the entry boundary and pass it into application services. Do not allow DTO/body tenancy to become authorization. ## 21. Add first-class idempotency for retry-prone operations Apply stable idempotency semantics to: - Signal/email/webhook intake; - offline replay; - outbox consumers; - external integration operations; - workflow actions that can be retried. Prefer unique constraints/records scoped by organization + operation/source + idempotency key. Retries must not create duplicate Work or external effects. ## 22. Add a transactional outbox and Orgo worker External or long-running effects should not run inline inside the Work transaction. Introduce an `OutboxMessage` model and worker process sharing the same Orgo code/release/database contract. ```text business mutation + outbox row → commit → worker claim/process → retry/backoff → completed or terminal/manual state ``` Start with a Postgres-backed poller (`FOR UPDATE SKIP LOCKED` or equivalent). Do not introduce Kafka/RabbitMQ/Redis solely to satisfy the pattern. ## 23. Add IntegrationOperation and per-system ACLs Add an Orgo-owned external-operation record for provider, operation, Work subject, idempotency/correlation, status, external reference, receipt/error and timestamps. Implement separate ports/adapters/Anti-Corruption Layers for Kristal, Konnaxion, Architect and other independently owned systems. External SDK/domain models must stop at the adapter boundary. Never overload Task/Case status with external lifecycle state. ## 24. Separate inbound email from outbound communications The current Email area mixes ingestion and delivery concerns. Target split: ```text inbound email -> Intake adapter -> Signal Notification -> outbound email channel adapter ``` This removes avoidable coupling between parsing/intake and notification delivery. ## 25. Normalize event semantics The snapshot contains TaskEvent, WorkflowTransitionEvent, ActivityLog, SecurityEvent and logger-only event recording patterns. Define and enforce three categories: ```text domain/work event audit/security event integration message ``` Unify important Task/Case transition persistence so equivalent mutations do not sometimes create durable events and sometimes only write logs. ## 26. Keep Insights as light CQRS/read projections Consolidate the current duplicate Insights implementations and define a read/projection interface. Do not require a separate ORM/warehouse for architectural purity. Use the existing database/materialized views first when sufficient; separate storage is an optimization when measured needs justify it. Read models may optimize My Work, Supervisor, Operations dashboards and reporting, but must never write operational state directly. ## 27. Apply resilience only at faillible boundaries For external/async adapters use, as appropriate: - timeouts; - bounded retry; - exponential backoff with jitter; - circuit breakers; - concurrency/bulkhead limits; - DLQ/manual redrive for poison/permanent async failures. Fallback/degradation must preserve semantics. Required validation/recognition may become waiting/blocked/degraded, never silently approved. ## 28. Add structured observability and health semantics Propagate request/correlation/causation and relevant organization/Signal/Case/Task/workflow/integration-operation identifiers across logs and traces. Add metrics for queues/outbox, failures, retries and workflow/integration latency. Expose distinct liveness/readiness semantics. Optional hosts such as Koali Spaces must not make standalone Orgo unhealthy when absent. ## 29. Enforce architecture boundaries in CI Documentation alone will not preserve a modular monolith. Add dependency tests/lint rules that reject patterns such as: ```text domain -> raw Task/Case persistence Insights -> operational mutation integration -> Prisma mutation of Orgo core Work -> domain-internal implementation core -> external provider model ``` Permit modules to depend on explicit public contracts/APIs rather than internal implementation paths. ## 30. Do not prematurely distribute the monolith Do not introduce Task, Case, Workflow or Notification network services, Event Sourcing, mandatory broker infrastructure, service mesh, sharding or cell architecture as part of the current alignment. Reconsider them only after measured scale/reliability requirements show that the modular monolith is the limiting factor. ## Recommended implementation order ```text 0 build/test/boot truth + imports/routes/config 1 Work ownership + module dependency enforcement 2 ExecutionContext + persisted Signal + idempotency 3 ActionExecutor + WorkflowVersion + Outbox/worker 4 IntegrationOperation + ACL adapters 5 Insights/read projections + observability/resilience 6 Case-centered product UI + external ecosystem workflows ``` ================================================================================================ FILE: Docs/Technical-Reference/COMPLETION_DECISIONS.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 4ef41a73829d18a5c7b99ccfbe74bb1e8b693b7843d1533d566fa492143030e6 CONTENT_BYTES: 9200 ================================================================================================ # Orgo — completion implementation decisions (2026-09-09) This document records concrete refinements to the target architecture. It accompanies executable source; it is not a replacement target or a claim of completed local acceptance. ## Durable orchestration `WorkflowService` still evaluates a frozen workflow version and commits its internal actions and external intents in a transaction. `ACTIONS_COMMITTED` does not mean external validation succeeded. The new `START_PROCESS` action creates a `DurableProcess` in that same transaction. The process also has its own authenticated HTTP creation endpoint. A process freezes a plan and its hash, subject and tenant. Its worker executes ordered integration, human-approval and timer steps. The durable states are `RUNNING`, `WAITING_EXTERNAL`, `WAITING_HUMAN`, `WAITING_TIMER`, `BLOCKED`, `COMPLETED`, `CANCELLED`. Steps record results; transitions increment an optimistic revision. Polling rotation touches `updated_at` without continually invalidating a human's revision. Process locks serialize decisions and advancement. Each integration step can declare `expect`, a map of paths within the final receipt's `data` to primitive expected values. A validation requirement must explicitly state its predicate, for example `{"expect":{"validated":true}}`. A transport success alone is not an approval. Predicate mismatch blocks the process. The supplied validate/publish example requires both a positive validation receipt and human approval. The integration bridge can return `accepted` or `succeeded`. `accepted` leaves the operation running until an authenticated final callback. Callbacks require both `integrations:callback` and the provider permission, such as `kristal:callback`. Use a dedicated tenant token with these permissions, not an administrator session. Conflicting terminal receipts are rejected. `REQUEST_INTEGRATION` remains available independently of processes. External timeouts block. Retrying an outbox failure preserves the original operation identity. A callback that explicitly reports a final failure requires a deliberate new process if the operator wishes to make a new external request. Pending operations are never automatically duplicated. Cancelling a process stops its orchestration; it cannot undo or retract an already-dispatched external request. A compensation is a separate reversed plan assembled only from successful steps that explicitly declare compensation requests. A still-pending external request must settle before compensation. Compensation requests must be supported by the configured provider adapter; none are fabricated. The initiating user's or API token's current permissions are reloaded when the worker advances. A revoked principal blocks the process. An authorized operator with `workflows:manage` may adopt a blocked process, with a reason and revision; adoption does not implicitly approve or retry a step. ## Work scope and evidence Global roles keep their existing meaning. Existing scoped `UserRoleAssignment` rows now contribute explicit `workGrants` for team, location, unit or custom references. Only explicit `work:*` permissions are activated from scoped roles; a scoped wildcard never grants administration rights. Scope assignment APIs require the role to contain `work:read`. Role grants and scopes are included in idempotency fingerprints. Tasks and Cases have dedicated `access_scope_type` and `access_scope_reference` columns. They are not authorization fields hidden inside arbitrary metadata. Both must be present or both absent. Read filters, restricted visibility and parent visibility are enforced together. Each mutation checks its permission against the actual subject scope. Task and parent Case scopes must match. Scope references are administrator-defined identifiers, not a claim that a separate organizational hierarchy engine has been implemented. Evidence uses a Work-owned table with bounded database content (1 MiB per file), a SHA-256 digest, filename, media type and audit event. Downloads require current subject access and are forced to file download by the UI. Deletion is a tombstone. Explicit retention can purge tombstoned bytes while retaining the digest and immutable audit trail. Large-file object storage and antivirus services are extension points, not bundled services. Typed Work relations are references. `blocks` is visible relationship data; it does not silently introduce a new Task lifecycle rule. Task reparenting preserves restricted visibility when leaving a restricted Case. Archived Cases and terminal Tasks reject applicable edits. Title/description edits, case edits, paged timelines and attachment UI are connected. ## Identity and account lifecycle Local login uses scrypt and hashed opaque sessions. Password creation/reset never caches plaintext secrets in command responses. Account-creation idempotency fingerprints the identity fields, not the password; replaying account creation does not change its original credentials. Password changes have a separate authenticated endpoint and terminate existing sessions. API-token secrets are returned only in the initial successful response and are not stored in the idempotency response. If that response is lost, the caller can see the token metadata, revoke it, and issue another token. Invitations and recovery links are single-use, hashed at rest in the challenge table and expire after one hour. The delivery queue necessarily holds the link while it is being delivered; retention and access to notification storage must reflect that. The browser receives the challenge in a URL fragment, removes it from browser history, and submits it over the API. OIDC is optional: one configured HTTPS issuer, authorization code flow, S256 PKCE, browser-bound HttpOnly state cookie, nonce, RS256 signatures using discovered JWKS, issuer/audience/authorized-party/time checks, and explicit tenant + issuer + subject enrollment. No email-based auto-linking occurs. Unknown subjects are rejected. Supported deployments use the web's same-origin API proxy and HTTPS. Provider logout, SAML, SCIM and automatic enrollment are not implied. References for the implemented protocol subset: - https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation - https://www.rfc-editor.org/rfc/rfc7636.html Login, recovery and SSO limits use PostgreSQL buckets shared across API instances. Expired buckets and OIDC attempts are cleaned by the worker. ## Domains, communication and read side Maintenance exposes assets, task creation and non-overlapping asset reservations with explicit calendar transitions. HR exposes restricted Case/Task creation, participants, review transitions and wellbeing records. HR review status remains separate from the operational Case lifecycle. Education exposes groups, scoped person validation, membership lifecycle and linked support tasks. No new domain code writes raw Task/Case tables. Notification templates use plain-text interpolation with required named values and no expression evaluation. In-app and SMTP remain native channels. SMS and webhook delivery use optional, fixed operator-configured gateway endpoints with stable idempotency keys; these are gateway contracts, not compatibility claims for a chosen vendor. The gateway must report delivery explicitly. Browser push is not represented as implemented. The Python MIME adapter supports individual EML files, mbox imports and IMAP polling using TLS. Messages are bounded before parsing/fetching; attachments are bounded and are never executed or rendered as trusted HTML. A message is marked Seen only after durable Orgo acceptance. Failures remain available for retry. Tenant authority comes only from the API token, never mail headers. Intake stores a compact Signal plus a separate immutable normalized email envelope/attachments, rather than passing attachment bytes into the workflow evaluator. Insights retains one PostgreSQL/Prisma read side with visibility-aware queries. CSV export, indexed pagination, operational gauges and structured request spans are implemented. A materialized warehouse is unnecessary for correctness and is not presented as completed merely because a target diagram mentions projections. ## UI and ecosystem Additional routes use shared forms and product-owned components. Workflow plans, permission arrays and free-form integration payloads retain structured JSON editors where their values are inherently structured. Ordinary domain/account fields have labeled controls. An explicit per-account local command queue supports preview, export, delivery and conflict correction; it never stores authentication tokens and does not silently replace a failed online mutation with apparent success. The hosted entry exports `OrgoApp`, `orgoSurface` and a permission-filtered command inventory. `orgo-surface/v1` is an Orgo-owned contract, not an invented Koali standard. A host imports the entry and Orgo styles and supplies routing. Actual Koali/Capsule contract packages and native provider protocols were not supplied in this workspace. Their final adapters/manifests must be based on those real contracts, not guessed names or shapes. ================================================================================================ FILE: Docs/Technical-Reference/CONTRACTS.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 41d8aa0a6d96ad8a3cd973c8cec981b28ac062622c9898e1dad5fdb938edcebe CONTENT_BYTES: 7155 ================================================================================================ # Orgo — Contract Surface > **Delivery reference (2026-09-09):** `IMPLEMENTATION_STATUS.md` distinguishes implemented behavior from the remaining target; `IMPLEMENTATION_DECISIONS.md` defines the adopted action syntax and migration refinements. ## 1. Public Task JSON boundary The intended public JSON contract uses snake_case: ```text task_id organization_id case_id source type category subtype label title description status priority severity visibility assignee_role created_by_user_id requester_person_id owner_role_id owner_user_id due_at reactivity_time reactivity_deadline_at escalation_level closed_at metadata created_at updated_at ``` Canonical Task enums: ```text status PENDING | IN_PROGRESS | ON_HOLD | COMPLETED | FAILED | ESCALATED | CANCELLED priority LOW | MEDIUM | HIGH | CRITICAL severity MINOR | MODERATE | MAJOR | CRITICAL visibility PUBLIC | INTERNAL | RESTRICTED | ANONYMISED source email | api | manual | sync category request | incident | update | report | distribution ``` Lower-case JSON representations may be accepted at selected boundaries and normalized explicitly. The stored/core enum remains unambiguous. ## 2. Task lifecycle Allowed transitions implemented by the core service: ```text PENDING → IN_PROGRESS | CANCELLED IN_PROGRESS → ON_HOLD | COMPLETED | FAILED | ESCALATED ON_HOLD → IN_PROGRESS | CANCELLED ESCALATED → IN_PROGRESS | COMPLETED | FAILED COMPLETED → terminal FAILED → terminal CANCELLED → terminal ``` `closed_at` is set when entering a terminal state. ## 3. Case boundary Canonical Case status: ```text open | in_progress | resolved | archived ``` Canonical Case source: ```text email | api | manual | sync ``` Canonical Case severity uses the Task severity vocabulary, represented lower-case at the public JSON boundary. Implemented lifecycle: ```text open → in_progress | resolved | archived in_progress → resolved | archived resolved → in_progress | archived archived → terminal ``` ## 4. Labels Canonical shape: ```text .[.] ``` Constraints implemented in the label routing service: - base: positive integer; - category digit: 1–9; - subcategory digit: 1–5; - optional role: dot-separated alphanumeric segments; - reserved broadcast bases: `10`, `100`, `1000`. Task categories remain: ```text request | incident | update | report | distribution ``` ## 5. Workflow rule contract Current Workflow Engine recognizes event sources: ```text EMAIL | API | SYSTEM | TIMER ``` and action types: ```text CREATE_TASK UPDATE_TASK ROUTE ESCALATE ATTACH_TEMPLATE SET_METADATA NOTIFY ``` The Workflow Engine itself is intentionally evaluation-oriented: it resolves ordered actions. Callers/executors perform side effects through the correct owner services. ## 6. Standard service result Core services use the result envelope: ```json { "ok": true, "data": {}, "error": null } ``` Failure: ```json { "ok": false, "data": null, "error": { "code": "STABLE_ERROR_CODE", "message": "Human-readable explanation", "details": {} } } ``` ## 7. Tenant boundary Any Task/Case mutation or sensitive lookup must resolve an organization explicitly and enforce it in the service query. A caller-provided header/body organization ID is an input to tenant scoping, not proof of authorization by itself. ## 8. Koali hosting and capability-projection contract Orgo must support standalone operation and Koali-hosted presentation without duplicating the business application. When hosted by Koali: ```text installed/admitted module manifest -> Koali GlobalShell -> Orgo local_module_surface -> Orgo router/UI ``` Koali capability projections are presentation data, not mutation authorization. A protected Orgo command must independently resolve and validate: ```text identity organization/tenant RBAC policy ``` The Orgo-to-Koali boundary may contribute routes, sidebar entries, widgets, required capability references and surface references using the canonical Koali module interface. It must not redefine a parallel global `Product/SurfaceProfile/Capability` taxonomy. ## 9. Orgo presentation-profile contract Presentation profiles are Orgo-internal UX compositions. They may select: - a home route; - navigation groups; - exposed actions/widgets; - search or command scopes; - Inspector policy; - density/presentation defaults. They do not grant business permission. Canonical initial profile vocabulary: ```text Full Control Panel Operations My Work Supervisor Intake Workflow Admin Executive Embedded ``` Exact profile names/configuration may evolve, but the composition-vs-authorization separation is invariant. ## 10. Execution-context contract Protected entry paths resolve a common application context before invoking owner services: ```text organization_id actor_user_id / actor_type authorization reference correlation_id causation_id idempotency_key (when applicable) source ``` The exact transport representation may differ by adapter. The semantic context must not be independently reconstructed with different rules in every controller. ## 11. Target Signal contract Signal is a first-class accepted intake object in the target architecture. The delivered Prisma schema now provides the canonical model; the historical snapshot did not. Target public/internal mappings should preserve at least: ```text signal_id organization_id source external_reference idempotency_key type/classification/severity title/description payload or payload_ref status received_at processed_at ``` Acceptance flow: ```text normalize -> idempotency/deduplication -> persist -> orchestrate ``` ## 12. Reliable-effect contract Internal transactional effects execute through owner services. External or long-running effects are committed durably before execution. ```text business mutation + OutboxMessage → commit → worker → adapter → receipt ``` An `IntegrationOperation` tracks the Orgo-side lifecycle of an external request independently of Task/Case status. ## 13. Event taxonomy contract Do not conflate: - domain/work event — accepted business fact; - audit/security event — actor/compliance/security evidence; - integration message — durable request/result across an async/external boundary. ## 14. Workflow-version contract The target runtime truth is persisted and version-pinned: ```text WorkflowDefinition -> WorkflowVersion -> WorkflowInstance ``` A WorkflowInstance identifies the exact immutable version/hash used. YAML/filesystem definitions are import/export/authoring/seed artifacts, not a second runtime authority. ## Completion delivery reference — 2026-09-09 The active implementation and its remaining external-contract boundaries are recorded in `IMPLEMENTATION_STATUS.md`. See `COMPLETION_DECISIONS.md` for durable processes, receipt predicates, Work scopes, identity and evidence semantics; `ARCHITECTURE_TO_CODE.md` for source ownership; `LOCAL_VALIDATION.md` for the final acceptance to run locally. Historical validation results do not validate the completion changes. ================================================================================================ FILE: Docs/Technical-Reference/GLOSSARY.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 5c8356720877b3bb21330e7d6811f80782c54a2064f811bd596250d1083dce25 CONTENT_BYTES: 5487 ================================================================================================ # Orgo — Architectural Glossary ## Orgo **Orgo** is an ecosystem system and workflow/control platform. In a kOA-Linux deployment it may be called an integrated subsystem from the host scope, without transferring Orgo's internal authority. ## Module `module` is not a sufficient architecture category by itself. Within Orgo, prefer: - **core service/module** — Task, Case, Workflow, Labels, Config, Logging, Email, Signals, Notifications, Offline Sync; - **domain module** — Maintenance, HR, Education and other adapters around the core; - **application/web surface** — UI/API presentation; - **external ecosystem system** — Konnaxion, Kristal, SemantiK Architect, kOA-Linux. ## Organization The tenant/operational boundary. Orgo work belongs to an organization unless a contract explicitly defines global configuration. `organization_id` is an isolation key, not a generic universal scope shared with every external system. ## User vs Person - **User account** — login/actor identity in Orgo. - **Person profile** — human subject the work may concern, whether or not that person logs in. These identities are not interchangeable. ## Work The central operational bounded context that owns canonical Cases, Tasks, assignments, comments and work events. `Work` is an architecture/ownership boundary, not a new database row replacing Case or Task. ## Signal An accepted incoming fact/request/evidence object that may lead to or enrich work. Examples include API input, email, UI input, offline synchronization or system/timer events. In the target architecture Signal is persisted as a first-class Orgo object before retry-prone orchestration. The current Prisma snapshot does not yet contain that canonical Signal model. A Signal is not automatically a Task or Case. ## Task The canonical unit of work. A Task owns its Orgo lifecycle, classification, assignment, SLA/escalation and audit state. Domain-specific data belongs in typed domain extensions or metadata; it must not redefine the canonical Task lifecycle. ## Case A durable container for related Tasks, context and treatment over time. A Case is not identical to an external domain object. Example: ```text Orgo Case ≠ Konnaxion Topic ``` ## Workflow The Orgo rule/process layer that evaluates signals/state and resolves actions. Workflow execution determines operational actions; it does not become the owner of an external system's domain state. ## Domain module A domain-specific adapter/refinement over the common Task/Case core. A domain module may own additional domain tables (for example HR case details or maintenance asset links) while preserving the canonical Orgo Task/Case records as the work backbone. ## DomainTask A domain-centric **projection** of a canonical Task. It is not a second Task table or independent lifecycle. ## Label The canonical routing/classification string: ```text .[.] ``` Example: ```text 100.94.Operations.Safety ``` The label informs routing and classification. It does not replace explicit authorization or ownership. ## Broadcast label A label using a reserved broadcast base such as `10`, `100` or `1000`. It is informational by default. A mandatory Task is created only if an explicit workflow rule says so. ## Organization profile A versioned behavioral configuration for an organization, covering defaults such as reactivity, transparency, pattern sensitivity, retention and automation. A profile tunes the core; it does not create a new Task/Case schema. ## Cyclic overview Recurring review/pattern-detection behavior that analyses operational state. A detected pattern becomes governed work only through explicit Case/Task creation. ## Insight / report A derived analytical/read model. It does not become the authoritative owner of the operational Task/Case records it summarizes. ## Charter A semantic reference/configuration layer describing domain concepts and selected Wikidata mappings/refinements. It does not create a parallel operational ontology or lifecycle. ## External artifact reference A reference to an artifact owned by another system. Orgo may store the reference/correlation/receipt needed for workflow without copying the external artifact's entire schema into the core Task/Case model. ## Receipt Structured evidence that an operation was accepted, rejected or executed. A receipt supports workflow reconciliation; it is not the external system's authoritative state. ## ExecutionContext The resolved tenant/actor/request context passed into protected application operations. It carries organization identity, actor identity/type, authorization reference, correlation/causation identifiers, source and optional idempotency key. ## OutboxMessage A durable infrastructure record written atomically with a business transaction so a post-commit action/event can be processed reliably by the Orgo worker. It is not the business status of the external operation. ## IntegrationOperation An Orgo-owned operational record for a request to an external system, including provider/operation, Orgo subject, idempotency/correlation identity, status, receipt and error. It prevents external lifecycle states from being folded into Task/Case status. ## Domain event A business fact emitted after an accepted Orgo state transition, such as `TaskAssigned` or `CaseResolved`. Domain events are distinct from audit/security evidence and integration messages. ================================================================================================ FILE: Docs/Technical-Reference/IMPLEMENTATION_DECISIONS.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 0fe33a3a2e70e8fc5bb05ad3745bf025e7ee39e2304785455eb20de796e220f3 CONTENT_BYTES: 9038 ================================================================================================ # Orgo — Implementation decisions, 2026-09-09 This file refines `TARGET_ARCHITECTURE.md` for the delivered code. It does not replace product ownership or lifecycle contracts. ## 1. Replace broken runtime slices; preserve physical state The user authorized prioritizing documentation over negligible legacy code. The snapshot's active Nest graph referenced nonexistent modules, mixed two persistence stacks and exposed incompatible tenant/DTO conventions. Instead of preserving those as live parallel code, the supplied API/web source is retained under `legacy/`; new active modules use the **same Task, Case, organization, role and domain-extension tables**. This is an authorized implementation change from the earlier repair-first migration sequence, not a second operational model. Root workspaces now contain `apps/api` and `apps/web`. The former starter `packages/*` remain reference material and are not runtime dependencies. The shared application UI is owned by Orgo. ## 2. Signal acceptance is a separate committed transaction `POST /signals` persists the normalized Signal and, when requested, an outbox message containing an immutable workflow-version reference. It does not synchronously execute workflow effects. This ensures a later invalid action cannot erase accepted input. The worker re-resolves the initiating user's current permissions, or the initiating API token's current scopes. A deactivated principal cannot execute an old privilege snapshot. Intake processing locks the Signal, creates Work/instance/link rows and acknowledges the message in one transaction. A failed action rolls these back; the accepted Signal remains `RECEIVED` and the message exposes its retry/dead state. `REJECTED` is reserved; there is currently no rejection endpoint. External-reference uniqueness is organization + source + external reference. Reusing that identity with changed normalized input returns a conflict rather than silently changing evidence. ## 3. A workflow can start before any Task exists The old `WorkflowInstance.task_id` was required. It is now nullable; new instances always pin `workflow_version_id`, and may also refer to a Signal. Existing rows retain nullable version references for explicit legacy migration. No version is fabricated from an incompatible old YAML/blob. A definition's `definition_blob` remains a compatibility mirror of its latest publication. Runtime evaluation reads `WorkflowVersion.content` only. Published versions have an SQL immutability trigger. Definitions use organization-scoped codes; global workflow inheritance is not implemented. Instance `completed / ACTIONS_COMMITTED` means internal actions committed and external requests were queued. It **does not mean** an external validation approved anything. Long-running business process managers that wait for external receipts remain separate future work. ## 4. Idempotency and concurrency All ordinary mutation routes require `Idempotency-Key`; login/logout do not. Email may fall back to its message identity; offline replay supplies a UUID for each command. Commands take a transaction-scoped PostgreSQL advisory lock on organization + operation + key. The request fingerprint includes input, principal and current authorization context. A replay returns the stored response; different input or a changed authorization context conflicts. Task/Case mutation routes also recheck current visibility before replay. Work status/assignment/edit operations require `revision`. Compare-and-update prevents lost updates; accepted updates increment it. Case archival and task attachment share a Case lock. Case reopening and Task terminal states follow the canonical transition tables. The outbox uses `FOR UPDATE SKIP LOCKED`, a 60-second lease, a token that fences acknowledgements, heartbeat renewal, eight attempts and bounded exponential backoff with jitter. Dead messages can be manually redriven. Delivery is at least once; an external adapter must implement durable deduplication with the supplied operation identity. SMTP cannot guarantee exactly-once delivery; a crash after SMTP acceptance can produce a duplicate despite the stable Message-ID. ## 5. Authorization and confidentiality One HTTP guard resolves the identity and organization from an opaque session token or organization-scoped API token. Headers/body values never grant tenancy. Sessions are stored by token hash; user roles and permissions are resolved from the database for every protected request. Local passwords use scrypt; legacy password hashes are not automatically converted. The initial authorization implementation admits organization-wide roles only (`global` or absent scope). It fails closed for unimplemented team/location/custom scopes. `work:restricted` gates restricted Cases and sensitive people. Restricted Tasks additionally admit their assigned user/role, subject to their parent Case remaining visible. HR creation forces restricted Case and Task visibility. The API returns 404 for inaccessible Work references. Composite tenant foreign keys protect Task Case/owner/requester references and Signal links. Cross-organization dirty legacy references must be corrected before the additive migration can apply; the migration does not silently reassign them. Login throttling is per API process and IP. Distributed rate limiting, SSO, password recovery and user invitations are not included. Seed supplies initial administration. Existing credentials are never overwritten implicitly. ## 6. Workflow authoring and action syntax The implemented version payload is `{ "rules": [...] }`. Rules have unique `id`, optional `enabled` (default true), strict match criteria and ordered `actions`. Each action is `{ "type": "...", "target": "...", "input": {...} }`. Supported actions: `CREATE_CASE`, `CREATE_TASK`, `UPDATE_TASK` (status only), `ASSIGN_TASK`, `ROUTE`, `ESCALATE`, `SET_METADATA`, `ATTACH_TEMPLATE`, `ADD_LABEL`, `NOTIFY`, `REQUEST_INTEGRATION`. `ROUTE` with empty input applies persisted routing rules; an explicit owner input uses the same Work assignment API. Routing resolves matching non-fallback rules first, then fallback rules; weight descending and ID break ties deterministically. `ADD_LABEL` adds an EntityLabel and leaves the primary classification label unchanged. `ATTACH_TEMPLATE` records a template reference; it does not call a document-generation engine. References are exact strings: `$signal.id`, `$signal.source`, `$signal.title`, `$signal.description`, `$signal.label`, `$signal.type`, `$signal.category`, `$signal.severity`, `$signal.payload`, `$case`, `$task`. The latter two refer to the latest result (or linked Case). They are explicit bindings, never evaluated code. An unavailable binding rejects execution. Simulation evaluates matches and returns action intents without invoking handlers or writing state; it is not a promise that every eventual effect will succeed. JSON publication and YAML import normalize into the same persisted contract. Historical action syntax must be explicitly converted; it is not silently interpreted as the new shape. ## 7. Presentation and optional hosting The React component is the same application in standalone and hosted modes. A host supplies path/navigation through `OrgoAppProps`; the component retains Orgo login and authorization. Profiles select a home and a composition of routes. They do not grant permissions or replace backend checks. `hosted-entry.tsx` is a code-level embedding boundary. The supplied files do not contain the executable canonical Koali/Capsule schema packages; no native manifest compatibility or admission is claimed. Wiring the exported surface into those actual contracts remains an integration step. No second global shell, private provider frontend import, or required Spaces dependency was introduced. ## 8. Data and deployment The new migration is additive to the supplied migration history. Test it against a restored copy of any existing database before applying it there. Historical migrations are preserved as provided, including their original legacy User-table removal; they are not a recommended import path for an unrelated existing database. API and worker use the same Prisma schema, modules and release. Insights reads grouped operational data through Prisma and cannot mutate it. The existing star schema remains available for later projections; no second ORM, broker or mandatory warehouse is introduced. Observability currently supplies correlation identifiers, history, error logs and liveness/readiness; full metrics/tracing export remains a documented gap. ## Completion supersession For the 2026-09-09 completion delivery, `COMPLETION_DECISIONS.md` supersedes earlier limitations concerning global-only Work permissions, completed-only bridges, missing process managers, identity administration, email ingress, offline UI and supplemental domain screens. The original architectural boundaries remain unchanged. Do not treat historical test counts as acceptance of the new code. ================================================================================================ FILE: Docs/Technical-Reference/IMPLEMENTATION_STATUS.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: ce086cef2e1c743c027689741cf9b661bd13923c4f39127ecc392764838cba1c CONTENT_BYTES: 6763 ================================================================================================ # Orgo — implementation ledger, completion delivery 2026-09-09 This ledger describes active source in this archive. The user will perform final validation locally. Implemented source and supplied tests are distinct from executed acceptance results. ## Active capabilities | Area | Implemented source and connected behavior | | --- | --- | | Architecture | One Nest API/worker release, one PostgreSQL database, modular Intake / Work / Orchestration; active imports enforced by architecture checks | | Work | Canonical Cases/Tasks, lifecycle and optimistic revisions, assignment, comments, edits, Case attachment/detachment, additive labels, scoped reads and mutations, immutable events | | Evidence | Work-owned file storage, content hashes, authorized download, tombstones, optional byte purge, typed relations, paged timelines and connected inspector controls | | Intake | Durable Signals, deduplication/fingerprint conflicts, pinned workflow version, email/webhook/offline adapters | | Email | EML and mbox import, TLS IMAP poller, bounded MIME parsing and attachments, durable normalized envelope, authorized attachment retrieval and UI; mark Seen after acceptance | | Workflow | Immutable JSON/YAML versions, pure evaluation/simulation, synchronous actions, outbox integration/notifications and `START_PROCESS` | | Long processes | Frozen plans, ordered external/human/timer steps, explicit receipt predicates, deadlines, blocking, revision-protected decisions, current-principal reauthorization, adoption, declared compensation processes | | External operations | Per-provider bridge ports, accepted versus succeeded receipts, authenticated final callbacks, terminal-receipt conflict detection and preserved operation identity on retry | | Worker | PostgreSQL claims/leases/heartbeats/fenced commit, bounded retries/dead messages/redrive, process advancement, SLA escalation, fleet heartbeat and housekeeping | | Authentication | Local scrypt, opaque sessions, logout, password change/recovery/invitation, single-use links, token issuance/revocation and account disablement | | SSO | Optional OIDC HTTPS authorization-code/PKCE flow, browser binding, nonce/issuer/audience/signature/time validation and explicit tenant/issuer/subject enrollment | | Permissions | Global roles plus existing scoped assignments activated as explicit Work grants for team/location/unit/custom; dedicated Task/Case scope fields and parent constraints | | Communications | In-app/SMTP, plain-text versioned templates, read state, optional fixed SMS/webhook gateways with explicit delivery receipt and idempotency key | | Maintenance | Assets, linked Work tasks, calendar reservations, overlap rejection and status transitions; product forms and calendar view | | HR | Restricted Work creation, participant lifecycle additions, review transitions, wellbeing records, product forms and detail view | | Education | Groups, member add/remove with tenant checks, linked support tasks, product forms and member view | | Read side | Scoped overview/workload queries, timeline/list pagination, bounded CSV export with formula neutralization and supporting database indexes | | Operations | Authenticated fleet/backlog/process overview, Prometheus gauges, structured HTTP spans, explicit retention, backup/empty-database restore scripts and legacy preflight | | Web | Shared product routes, profiles, operational forms, inspectors, identity/domains/process/communications/system/report views, account recovery and SSO entry | | Offline | Explicit browser-local per-account/API queue, preview/export/replay, stable command IDs, visible conflicts and correction using new command IDs; tokens never stored in the queue | | Public surface | Product-owned hosted entry, Orgo surface/route/profile export and permission-filtered command inventory; standalone has no Spaces dependency | | Delivery | New additive migration, endpoint inventory, architecture-to-code map, runnable local validation command and examples | ## Checks and acceptance status The implementation work includes Prisma client generation, TypeScript checking for API/tests/web, architecture dependency checks and Python/shell syntax checking. Current check output is under `validation/completion/`. **Final tests, application execution against the new migration, Docker builds/runs, browser acceptance, real provider delivery, OIDC interoperability, load/recovery and restoration validation have not been run for this completion delivery.** They are intentionally left to the user. Run `npm run validate:local` with an isolated `TEST_DATABASE_URL` and follow `LOCAL_VALIDATION.md`. The previous archive had 12 passing unit tests and 24 passing integration tests, with one native PostgreSQL test skipped in PGlite. Those are historical results only; they must not be read as results for the changes in this archive. New regression tests have been added for attachments, process gates/callbacks, scopes, maintenance overlap, MIME attachments and safe templates. ## Concrete boundaries - Native Kristal/Konnaxion/Architect/kOA schemas and SDKs, and canonical Koali/Capsule contract packages, are absent from the supplied workspace. The shipped bridges and `orgo-surface/v1` are explicit Orgo contracts. Their existence does not assert native compatibility or host admission. - A gateway must implement delivery/idempotency semantics for the chosen SMS or webhook provider. Browser push, a vendor-specific gateway and a built-in SMTP server are not claimed. The supplied email adapter consumes an existing IMAP server or mail archives. - Core workflows, domain operations and UI are implemented to the documented generic contracts. Organization-specific HR/education processes, provider receipt predicates, routing rules and compensation operations must be configured with actual policy/content. Example plans are examples, not automatic deployment policy. - Work scope identifiers are explicit authorization perimeters. A separate team/location hierarchy catalog or arbitrary policy language is not implied. - Evidence is bounded to 1 MiB per Work file and 1 MiB total attachments per incoming message. Mail source parsing is bounded to 2 MiB. Large-file object storage is not bundled. - The read side uses scoped operational queries and indexes. A separate analytical warehouse/materialized projection fleet is not required for this delivery and is not presented as implemented. - Legacy data may require reconciliation and credential reenrollment. The preflight and migration notes address this; no blind automatic repair mutates existing business data. These are the actual integration/configuration and acceptance boundaries. No endpoint fabricates external success or depends on Spaces to keep Orgo functional. ================================================================================================ FILE: Docs/Technical-Reference/INTEGRATION_BRIDGE.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 0da629b20f824ea1745da1cf040cd397e8863e3449827fa8174ce887a6365762 CONTENT_BYTES: 4218 ================================================================================================ # Orgo — Explicit integration bridge protocol The concrete APIs of Kristal, Konnaxion, Architect and kOA are not supplied. The adapters in `apps/api/src/orgo/integrations` implement the following **Orgo-owned bridge protocol**, not assumed native provider endpoints. A provider-side adapter must translate it and enforce its own authorization. Never point this code at a native API without an explicit compatible adapter. Configure one exact endpoint per provider: `KRISTAL_BRIDGE_URL`, `KONNAXION_BRIDGE_URL`, `ARCHITECT_BRIDGE_URL`, `KOA_BRIDGE_URL`, with the corresponding optional `_TOKEN`. Production requires HTTPS. Development permits HTTP on localhost/127.0.0.1 only. URLs come from deployment configuration, never request payloads; redirects are rejected. The worker POSTs JSON with a stable `Idempotency-Key`, `X-Correlation-ID` and optional bearer authorization: ```json { "operation_id": "uuid", "organization_id": "uuid", "operation": "validate", "idempotency_key": "organization-uuid:operation-uuid", "correlation_id": "correlation", "subject": { "type": "case", "id": "uuid" }, "input": {} } ``` Configured operation allowlists: | Adapter | Operations | | --- | --- | | Kristal | `validate` | | Konnaxion | `publish`, `distribute` | | Architect | `generate` | | kOA | `execute` | A successful, completed response is: ```json { "status": "succeeded", "external_reference": "provider-owned-reference", "data": { "valid": false } } ``` Here `succeeded` means the operation returned a receipt. `valid: false` remains false; delivery success is never approval, publication or a Work lifecycle transition by implication. The bridge must durably deduplicate operation IDs and return the same completed result on retries. The bridge may alternatively return `{"status":"accepted","external_reference":"ref","data":{}}`. This acknowledges durable acceptance only. The operation remains RUNNING until a final authenticated callback to `POST /api/v3/integration-operations/:id/receipt` with `Idempotency-Key` and a tenant API token carrying `integrations:callback` plus the provider-specific permission (for example `kristal:callback`). The final callback shape is `{"status":"succeeded"|"failed","external_reference":"ref","data":{},"error":"optional failure code"}`. Contradictory terminal receipts are rejected. `DurableProcess` waits for these receipts with an explicit deadline. To require a business predicate, declare `expect` on the integration step. Paths are relative to receipt `data`, for example `{"expect":{"validated":true}}`. A successful transport without that required value blocks the process. A completed workflow's `ACTIONS_COMMITTED` and a completed process still never mutate Work status by implication. Unsupported compensation operations are rejected by the same adapter allowlist. The adapter has a 10-second deadline, a 256 KB response limit, a circuit opening after five failures for 30 seconds, and a per-process limit of four active requests per adapter. The worker normally handles one delivery at a time. HTTP 408/409/425/429 and 5xx retry; other failed responses are terminal. No response body, bearer token or configured URL is copied into an error log. Outbox delivery is at least once. Retries use the same external identity. No external network effect runs inside a Work transaction. IntegrationOperation holds request metadata, receipt, external reference and errors independently of Case/Task status. For notifications, `in_app` delivery is implemented; email uses configured `SMTP_URL` and `SMTP_FROM`. SMS and webhook delivery can use fixed `SMS_GATEWAY_URL` / `WEBHOOK_GATEWAY_URL` endpoints and corresponding `_TOKEN` variables. The endpoint is configured by the operator, never taken from a recipient address. POST payload: `{id, organization_id, recipient, subject, body, correlation_id, channel}` with stable organization/notification Idempotency-Key. A gateway must durably deduplicate and return `{"status":"delivered"}` only when its delivery contract is satisfied. A generic gateway is not a native SMS vendor adapter. Browser push is not implemented. SMTP uses a stable Message-ID but does not provide exactly-once guarantees. ================================================================================================ FILE: Docs/Technical-Reference/LOCAL_VALIDATION.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 2773d9d3298d4fc43b442cdf88d5b806ee8bca0fd7fbabcce2f8d53118e7acbc CONTENT_BYTES: 5403 ================================================================================================ # Validation locale — à exécuter par le propriétaire Les nouveaux tests sont livrés sans exécution finale dans cet environnement, conformément à la demande. Les résultats de l'archive précédente restent historiques. Cette livraison fait l'objet de contrôles statiques, pas d'une certification fonctionnelle ou de déploiement. ## Base de validation neuve Utiliser Node 22+, npm et PostgreSQL 16. Extraire l'archive dans un répertoire neuf. Créer une base isolée `orgo_test`, jamais une base de production. ```bash npm ci export TEST_DATABASE_URL='postgresql://USER:PASSWORD@localhost:5432/orgo_test?connection_limit=5' npm run validate:local ``` Le script génère Prisma, applique les migrations, contrôle les frontières et les types, puis exécute les tests unitaires/d'intégration et les builds. Il s'arrête au premier échec et écrit les résultats dans `validation/local-/`. Les identifiants de connexion réels restent dans votre environnement. Sous Windows, utiliser WSL pour les scripts shell et ce lanceur. Le test natif `FOR UPDATE SKIP LOCKED` doit être exécuté sur PostgreSQL, pas seulement PGlite. Les nouveaux scénarios couvrent fichiers/tenants, étapes humaines/révisions, réception asynchrone, périmètres Work, chevauchements de calendrier et pièces jointes email. Le test de template est purement local. ## Démarrage et navigateur Configurer `.env` depuis `.env.example`, puis suivre le README pour Compose, migration et création du compte initial. Vérifier les parcours avec au moins deux organisations et un utilisateur limité à un périmètre. - Connexion/déconnexion ; rôles et droits révoqués pris en compte à la requête suivante. - Création et édition de Case/Task ; transitions et conflits de révision ; rattachement à un Case ; visibilité restreinte et périmètres cohérents. - Upload/téléchargement/retrait d'une pièce jointe ; historique paginé et relations ; aucun accès depuis un autre tenant. - Signal manuel et email, version de workflow épinglée, redémarrage API/worker entre acceptation et traitement. - Processus en attente humaine, minuterie et reçu externe ; refus/predicate négatif/timeout ; reprise et adoption ; compensation uniquement lorsqu'elle est déclarée et applicable. - Gestion utilisateurs/rôles/jetons, invitation et mot de passe oublié via un SMTP de test. Vérifier qu'un secret de jeton n'est pas réaffiché lors d'un rejeu. - OIDC sur une origine HTTPS et un fournisseur de test : subject explicitement inscrit, state/nonce invalide, mauvais issuer/audience/signature, compte désactivé, code réutilisé. - Maintenance : réservation concurrente du même équipement ; RH : participants/revue/confidentialité ; éducation : ajout/retrait d'un membre et tâche de soutien. - Notifications, templates, lecture, SMTP et gateways choisies. - File hors ligne : commande créée sans réseau, reconnexion, rejeu, conflit de révision et correction explicite ; changer de compte ne doit pas exposer la file d'un autre compte. - CSV (y compris un titre commençant par `=`), pagination, navigation clavier et petits écrans. - Mode standalone sans Spaces ; mode hébergé avec les vrais contrats Koali lorsqu'ils seront disponibles. ## Reprise de données existantes Les anciennes migrations du snapshot sont conservées. Certaines migrations historiques remplacent d'anciennes tables : ne pas les rejouer aveuglément sur une base déjà peuplée. Faire une sauvegarde et vérifier l'historique Prisma avant migration. ```bash export DATABASE_URL='postgresql://.../orgo_existing' npm run migration:preflight bash scripts/operations/backup.sh /chemin/prive/orgo-before.dump ``` Le précontrôle ne modifie rien et signale les liens de tenant incohérents, intervalles invalides et comptes nécessitant une réinscription de leurs credentials. Il expose uniquement des identifiants échantillonnés, pas les mots de passe. Réconcilier les données et l'historique avant `prisma migrate deploy`. Les contraintes nouvelles sur des tables historiques marquées `NOT VALID` contrôlent les nouvelles écritures mais nécessitent `VALIDATE CONSTRAINT` après réconciliation des anciennes lignes. Restaurer dans une base dédiée vide et vérifier fonctionnellement la restauration : ```bash export RESTORE_DATABASE_URL='postgresql://.../orgo_restore_test' bash scripts/operations/restore.sh --restore-to-empty-database /chemin/prive/orgo-before.dump ``` ## Exploitation et contrats externes Tester une panne SMTP/fournisseur, des callbacks tardifs/dupliqués/contradictoires, la mort d'un worker après envoi mais avant acquittement, et le redémarrage avec backlog. L'idempotence côté fournisseur reste nécessaire pour des effets externes effectivement uniques. `GET /api/v3/system/overview` donne l'état des files/processus/workers. `GET /api/v3/system/metrics` fournit des gauges Prometheus avec authentification et permissions d'exploitation. Les logs HTTP sont des spans JSON sur stdout. Collecteur, alertes, sauvegardes planifiées et politique de rétention sont à configurer dans l'environnement de déploiement. Les contrats natifs Kristal/Konnaxion/Architect/kOA et Koali/Capsule sont à fournir et à vérifier séparément. Les bridges et le contrat public Orgo livrés sont explicites ; ils ne déclarent pas une compatibilité native non démontrée. ================================================================================================ FILE: Docs/Technical-Reference/Semantic-Charters.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: ecb6cd50387aadf9821ba0a9faa2b111257038c0393a6a70814081f36c0ee7ca CONTENT_BYTES: 7137 ================================================================================================ # Orgo — Semantic Charter Reference ## Scope Orgo charters provide a semantic vocabulary/reference layer using selected Wikidata QIDs/properties plus Orgo refinements. They **do not replace** the canonical Task/Case/workflow model, do not create a second lifecycle, and do not give external Wikidata state write authority over Orgo. Charter composition is a classification/semantic concern; operational work still enters the Orgo core through explicit signals, Cases, Tasks and workflow rules. --- ## 1) Goal and constraints **Goal:** Orgo represents organisational knowledge (tasks, roles, cases, processes, resources) as a graph using **Wikidata-compatible identifiers** so data can stay interoperable. **Constraints:** * Orgo must run in a **closed/offline bubble** (no heavy external LLM dependency). * Orgo must stay usable for **any organisation**, by composing reusable “families” + small domain specialisations. --- ## 2) What we reuse from Wikidata (and what we don’t) ### Reused “as-is” * **QIDs (`Q…`)** for concepts/items (roles, objects, concepts, places, etc.). * **Property IDs (`P…`)** when a property is universal enough and matches Orgo’s meaning. ### Not reused “as-is” * Wikidata’s full statement graph is **not imported**. Orgo creates its own relations between filtered Q-items, focused on organisational workflows. ### Licensing note (data vs software) * Wikidata data is published under **CC0 (“No rights reserved”)**, including official access channels and dumps. * Wikibase (the software behind Wikidata) is **GPL-licensed** (software licensing is separate from data licensing). --- ## 3) Identifier spaces in Orgo ### 3.1 QIDs (concepts) * **`Q####`**: Concepts/items aligned with Wikidata QIDs. * Orgo maintains a **filtered subset** of Wikidata items (QIDs) relevant to organisations. ### 3.2 P (public/universal properties) * **`P####`**: Properties identical to Wikidata property IDs when the meaning is universal and compatible. ### 3.3 R (Orgo workflow refinements of P) R are generic Orgo workflow relations that refine a base Wikidata property. **Rule:** * If `based_on` is `P####`, then `id` must be `R####NNN` (3-digit sequence). Example: * `R710001` (default responsible for) based on `P710` * `R710002` (assigned to) based on `P710` ### 3.4 S (Orgo-specific properties) S are Orgo properties that **do not exist as a Wikidata P**, but where we still want numeric alignment with the closest `P####` *when possible*. **Rules:** 1. If `based_on` is `P####`, then `id` must be `S####NNN` (3-digit sequence). * Example: if based on `P1552`, first specialisation is `S1552001`. 2. If `based_on` is `null`, use the reserved Orgo-only range: * `S0000NNN` (3-digit sequence). --- ## 4) Charter architecture (3 levels) All charts are JSON files in a flat folder. ### Level 1: global base * `/charters/general.json` Contains: * universal **P** (reused Wikidata properties) * universal Orgo workflow **R** (derived from P) * universal Orgo-only **S** (no `P` match) like visibility/editability. ### Level 2: families (each refines `general.json`) * `/charters/care.json` * `/charters/programs.json` * `/charters/operations.json` * `/charters/groups.json` * `/charters/incidents.json` These add **family-specific S** (and rarely P/R if needed). ### Level 3: domains (each refines exactly one family) Examples we established: * `/charters/care_hospital.json` * `/charters/care_school.json` * `/charters/care_social_services.json` * `/charters/programs_government.json` * `/charters/programs_humanitarian.json` * `/charters/operations_manufacturing.json` * `/charters/operations_transport_logistics.json` * `/charters/operations_facilities.json` * `/charters/groups_sports.json` * `/charters/groups_associations.json` * `/charters/incidents_sst.json` * `/charters/incidents_it_helpdesk.json` **Principle:** create a Level-3 file only when the domain introduces **new relation types**, not just different wording. --- ## 5) JSON file standard (schema) Every charter file follows the same top-level structure: ```json { "P": [ { "id": "P####", "label_en": "...", "wikidata_label_en": "..." } ], "R": [ { "id": "R####NNN", "based_on": "P####", "label_en": "..." } ], "S": [ { "id": "S####NNN", "based_on": "P####", "label_en": "..." }, { "id": "S0000NNN", "based_on": null, "label_en": "..." } ] } ``` **Field rules:** * `id`: required * `label_en`: required (Orgo label) * `wikidata_label_en`: optional (only meaningful for P) * `based_on`: required for R/S; `P####` or `null` --- ## 6) Composition/inheritance rules Orgo loads charts in this order: 1. `general.json` 2. one family chart (`care.json`, `operations.json`, etc.) 3. optional domain chart (`care_hospital.json`, etc.) Merge behavior: * Same `id` must not be defined twice. * If two charts need similar semantics, they must create distinct IDs (`…001`, `…002`, …). * Domain charts should prefer **S** that align to the closest `P####` (`S####NNN`) rather than `S0000NNN`. --- ## 7) Building Orgo’s QID subset from Wikidata (offline-friendly) ### 7.1 Input * Wikidata dumps / exports (CC0). ### 7.2 Filtering concept Orgo stores only the Q-items needed for organisational reasoning, using filters such as: * “organisation/role/task/process/resource” relevance * removal of irrelevant domains (celebrities, astronomy, etc.) * optional domain packs (hospital, government) that add more Q-items ### 7.3 Update process (repeatable) 1. Download/refresh dump snapshot. 2. Run Orgo filters to produce: * `qitems_core` subset * optional domain subsets (e.g., hospital pack) 3. Rebuild Orgo indexes (labels, aliases, search keys). 4. Leave Orgo’s **relations graph** intact (Orgo relations are authored separately). --- ## 8) From user input to QIDs (without heavy LLM) Orgo needs a local “lexicon layer” to map text → QIDs. Recommended offline approach (lightweight): * tokenization + normalization (casefolding, accents) * dictionary/alias tables (Orgo curated) * string similarity (Levenshtein, trigram) * BM25-style retrieval over labels/aliases * optional lightweight embeddings (local) if needed, but not required Output: * candidate QIDs with confidence scores * user-facing disambiguation when multiple close QIDs --- ## 9) Charter/reference charts Core/base: * `/charters/general.json` Families: * `/charters/care.json` * `/charters/programs.json` * `/charters/operations.json` * `/charters/groups.json` * `/charters/incidents.json` Domains already drafted: * `/charters/care_hospital.json` * `/charters/care_school.json` * `/charters/care_social_services.json` (Other domain paths are part of the target architecture; their content follows the same standard.) --- ## 10) Naming/numbering summary (the “hard rules”) * **P**: `P####` (Wikidata property IDs) * **R**: `R####NNN` where `####` = base P number, `NNN` = 001..999 * **S**: * `S####NNN` if based on `P####` * `S0000NNN` if `based_on = null` * Domain/family/general are **file-level**, not encoded in the ID. ================================================================================================ FILE: Docs/Technical-Reference/TARGET_ARCHITECTURE.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: ddb637b0e2b09ee3be3b9ba961bbaf1e5a47ad4192d49221f4d6ae68e9b2f453 CONTENT_BYTES: 17758 ================================================================================================ # Orgo — Target Architecture > **Delivery reference (2026-09-09):** `IMPLEMENTATION_STATUS.md` distinguishes implemented behavior from the remaining target; `IMPLEMENTATION_DECISIONS.md` defines the adopted action syntax and migration refinements. **Status:** Canonical target architecture for Orgo vNext. **Relationship to the current snapshot:** this document defines the desired architecture. It does not claim that every module, model, route or worker described here already exists. Current implementation gaps are tracked in `CODE_ALIGNMENT_NOTES.md`; the physical database remains authoritative for what is actually persisted today. ## 1. Architectural thesis Orgo should evolve as a **modular monolith oriented around operational work**, with a deterministic transactional core and durable asynchronous boundaries for long-running or external effects. ```text ORGO Modular Monolith │ ┌───────────────────┼────────────────────┐ │ │ │ INTAKE WORK ORCHESTRATION Signals Cases + Tasks Workflow normalization assignments Routing deduplication comments Escalation │ work events Actions └───────────────────┼────────────────────┘ │ Domain events + Outbox │ ┌────────────┼─────────────┐ │ │ │ Communications Integrations Insights notifications Kristal projections channels Konnaxion reports Architect kOA ``` Cross-cutting platform capabilities: ```text Tenancy / Identity / RBAC ExecutionContext Configuration Persistence / transactions Idempotency Audit Observability ``` The target is **not** a network of Task/Case/Workflow microservices. Internal module boundaries are code and ownership boundaries first. ## 2. Primary bounded contexts ### 2.1 Intake Intake owns receiving and normalizing incoming facts/requests before they become work. Responsibilities: - accept input from HTTP/UI, email, webhooks, timers, offline replay and external integrations; - normalize source-specific envelopes into an Orgo Signal contract; - enforce idempotency/deduplication; - persist accepted Signals; - invoke orchestration/evaluation without directly mutating Task/Case tables. Target flow: ```text external input → inbound adapter → normalize → deduplicate / idempotency → persist Signal → evaluate / route → explicit work actions ``` ### 2.2 Work `Work` is the central operational bounded context. ```text Work ├── Cases ├── Tasks ├── Assignments ├── Comments └── Work Events ``` `Case` and `Task` remain distinct concepts: - **Case** = durable situation/context and primary operational workspace; - **Task** = canonical executable unit of work. They are grouped because they share transactional rules, tenant boundaries, actors, lifecycle evidence and domain-module integration. ### 2.3 Orchestration Orchestration owns process decisions, not the work records themselves. ```text Orchestration ├── Workflow evaluation ├── Workflow instances/versions ├── Routing ├── Escalation/SLA └── Action dispatch ``` The Workflow evaluator remains deterministic and side-effect free: ```text WorkflowContext → matching/version-pinned rules → ResolvedWorkflowAction[] ``` An Action Executor/Dispatcher applies the resolved actions through the owning modules. ### 2.4 Communications Communications owns outbound notification intent and delivery coordination. Delivery channels are adapters. ```text Notification → channel adapter ├── email ├── push └── other future channels ``` Inbound email does **not** belong to the same responsibility: inbound email is an Intake adapter that produces Signals. ### 2.5 Domain modules Maintenance, HR, Education and future domains refine Work. They may own extension state but must enter canonical work mutations through Work public APIs. ```text domain request → domain validation/context → Work public API → Case/Task → domain extension/link rows ``` ### 2.6 Insights Insights is a read/projection boundary. It may use materialized views, reporting tables or a separate warehouse when justified, but it is never the write authority for operational state. ### 2.7 Integrations Each external system receives its own explicit port/adapter and Anti-Corruption Layer (ACL). ```text Orgo core ↓ port KristalPort ↓ adapter + mapper Kristal ``` The same rule applies to Konnaxion, SemantiK Architect and kOA-facing operational integrations. ## 3. Signal becomes a first-class persisted object The supplied historical snapshot lacked a canonical persisted `Signal`. The delivered runtime now adds it; see `IMPLEMENTATION_STATUS.md` for tested coverage. A Signal represents accepted incoming evidence/input before or alongside the work it causes. Target logical fields include: ```text id organization_id source external_reference idempotency_key type / classification / severity title / description payload or payload_ref received_at processed_at status ``` Relationships should make the operational chain visible: ```text Signal ──► Case └─────► resulting Tasks (directly or through Case/action evidence) ``` A Case may accumulate several Signals over time. A Signal need not always create a new Case. ## 4. Workflow source of truth and versioning The target source of runtime truth is persisted, version-pinned workflow configuration. ```text WorkflowDefinition └── WorkflowVersion 1 └── WorkflowVersion 2 └── WorkflowVersion 3 │ └── WorkflowInstance pins version 3 ``` Filesystem/YAML remains useful as: - authoring format; - import/export format; - seed/configuration artifact; - test fixture. It must not remain an unrelated second runtime source of truth. A running WorkflowInstance must be able to identify the exact immutable ruleset/version/hash it used. ## 5. Action execution model Resolved workflow actions are classified by effect type. ### 5.1 Internal transactional actions Examples: ```text CREATE_CASE CREATE_TASK UPDATE_TASK ASSIGN_TASK SET_METADATA ADD_LABEL ``` These normally execute synchronously inside Orgo through owner services and, when required, one database transaction. ### 5.2 Durable asynchronous actions Examples: ```text NOTIFY KRISTAL_* KONNAXION_* ARCHITECT_* publish/distribute other long-running external effects ``` These use the transactional outbox pattern: ```text business mutation + OutboxMessage │ same DB transaction ▼ commit ↓ Orgo worker ↓ external/channel adapter ↓ receipt / retry / terminal failure ``` Do not perform a remote side effect between an operational database mutation and its commit. ## 6. OutboxMessage and IntegrationOperation are different concepts ### OutboxMessage Infrastructure delivery record answering: > What must be delivered/processed reliably after this transaction commits? Target fields include event/message type, aggregate reference, payload, status, attempt count, availability time, correlation/causation IDs and timestamps. ### IntegrationOperation Operational record answering: > What external operation did Orgo request and what happened to it? Target fields include: ```text organization_id provider operation subject_type / subject_id external_reference status idempotency_key correlation_id request metadata receipt/error started_at / completed_at ``` This prevents external states from leaking into `Task.status` or `Case.status`. ## 7. ExecutionContext is a platform primitive Every protected entry path resolves one execution context before application logic: ```text ExecutionContext organizationId actorUserId / actor type permissions or authorization reference correlationId causationId idempotencyKey source ``` Rules: - caller-supplied organization IDs are never authorization by themselves; - application services receive tenant/actor context explicitly; - controllers/adapters do not invent different tenant resolution rules per endpoint; - correlation/causation identity propagates into work events, audit and integration operations. ## 8. Idempotency is a first-class invariant Idempotency is required at retry-prone boundaries: - Signal ingestion; - email/webhook ingestion; - offline replay; - workflow external actions; - outbox consumers; - external integration operations. The effective uniqueness boundary should normally include organization + operation/source + idempotency key. Retries must not create duplicate business effects. ## 9. Event taxonomy Do not collapse every record into one generic event stream. ### Domain event A business fact produced by an accepted state transition. Examples: ```text SignalReceived TaskAssigned CaseResolved ``` ### Audit/security event Evidence of who/what performed or attempted an operation, including compliance/security context. ### Integration message A durable request/result crossing an asynchronous or external boundary. Examples: ```text KristalValidationRequested NotificationDeliveryRequested ``` Orgo may persist all three categories, but they have different semantics and retention/processing rules. ## 10. Persistence and CQRS policy Orgo remains state-oriented, not Event-Sourced. Canonical operational state lives in PostgreSQL/Prisma-backed models, with immutable history where useful. Use **light CQRS** only where read shapes differ materially from write shapes: ```text operational Work state ↓ events/projection update read projections ├── My Work ├── Supervisor workload ├── Operations dashboard └── Insights/reporting ``` A separate warehouse, ORM or broker is an implementation option, not an architectural requirement. ## 11. Runtime/deployment shape The expected deployment may contain multiple processes without becoming microservices: ```text orgo-web orgo-api orgo-worker postgres ``` `orgo-api` and `orgo-worker` share: - the same domain/application code; - the same module ownership rules; - the same release/version; - the same operational database contract. The worker handles outbox processing, retries, scheduled escalation, projection updates and long-running integrations. Start with a PostgreSQL-backed outbox worker. Introduce Redis/RabbitMQ/Kafka only when measured scale or delivery requirements justify a broker. ## 12. Resilience policy Apply resilience at faillible boundaries, not indiscriminately inside the monolith: ```text timeout bounded retry exponential backoff + jitter circuit breaker concurrency/bulkhead limits idempotency DLQ/manual intervention when async processing cannot progress ``` Graceful degradation must preserve business meaning. Example: failure of a required Kristal validation cannot be converted into implicit approval; the workflow must remain waiting/blocked/degraded according to policy. ## 13. Observability policy Operational flows should propagate structured identifiers when available: ```text request_id correlation_id causation_id organization_id actor_id signal_id case_id task_id workflow_instance_id integration_operation_id ``` Use three complementary signals: - logs explain individual behavior; - metrics detect system behavior; - traces connect distributed/async behavior. Health must distinguish at least liveness and readiness. Optional hosts such as Koali Spaces must not make standalone Orgo unhealthy merely because the host is absent. ## 14. Selective hexagonal architecture Do not create ports/repositories/facades for every CRUD table. Use explicit ports/adapters where they protect a meaningful boundary: - inbound HTTP/email/webhook/offline replay; - Kristal/Konnaxion/Architect/kOA integrations; - notification delivery channels; - persistence interfaces where domain tests/transaction ownership benefit; - optional infrastructure such as broker/warehouse implementations. External SDK/domain types must stop at the ACL/adapter boundary. ## 15. Dependency rules The dependency graph is more important than the folder names. ```text Domains ───────► Work public API Intake ────────► Orchestration public API Orchestration ─► Work public API Insights ──────► read/projection interfaces Integrations ──► Orgo application ports ``` Forbidden examples: ```text domain module ─X→ raw Task/Case persistence integration ─X→ Orgo DB mutation Insights ─X→ operational state mutation Work ─X→ HR/Maintenance/Education internals Orgo core ─X→ external provider model ``` Enforce these rules with architecture tests/linting, not documentation alone. ## 16. Target code organization A possible physical layout: ```text apps/api/src/orgo/ platform/ execution-context/ persistence/ transaction/ observability/ idempotency/ outbox/ config/ modules/ tenancy/ identity/ intake/ signals/ work/ cases/ tasks/ assignments/ comments/ events/ orchestration/ workflow/ routing/ escalation/ actions/ communications/ notifications/ domains/ maintenance/ hr/ education/ sync/ insights/ adapters/ inbound/ http/ email/ webhook/ outbound/ email/ integrations/ kristal/ konnaxion/ architect/ koa/ ``` This tree is illustrative. Ownership and dependency rules are normative; exact folder names may change during migration. ## 17. Patterns selected from the Senior Architect corpus | Pattern | Decision | |---|---| | Modular Monolith | **Primary architecture** | | Hexagonal Architecture | **Selective at meaningful boundaries** | | Anti-Corruption Layer | **Required for external systems** | | Idempotency | **Required at retry-prone boundaries** | | Transactional Outbox | **Required for durable post-commit effects** | | CQRS | **Light/read-side only** | | Circuit Breaker / timeout / backoff | **External/faillible boundaries** | | Bulkhead | **External/AI/high-cost workloads when needed** | | Graceful Degradation | **When semantically safe** | | DLQ/manual redrive | **Async poison/permanent failures when needed** | | Saga/process manager | **Only for long-running cross-system workflows** | | Broker Pub/Sub | **Not required initially** | | Event Sourcing | **Not selected** | | Microservices | **Not selected at current scale/shape** | | BFF as separate service | **Not selected currently** | | Sharding / Cell architecture / Service mesh | **Not selected currently** | ## 18. Migration strategy Use incremental replacement rather than a rewrite. ### Phase 0 — Make the snapshot truthful - repair imports/module graph/dependencies/config; - establish build/test/boot baseline; - normalize API routing; - remove/retire phantom and duplicate active implementations. ### Phase 1 — Establish module boundaries - group Task/Case under Work ownership; - establish Intake and Orchestration public APIs; - prevent domain modules from bypassing Work; - introduce architecture tests. ### Phase 2 — Durable intake/platform primitives - add persisted Signal; - add ExecutionContext; - add idempotency records/constraints where required; - propagate correlation/causation identifiers. ### Phase 3 — Reliable effects - add Action Executor/Dispatcher; - add OutboxMessage + worker; - reconcile WorkflowDefinition/Version/Instance; - make YAML import/export rather than competing runtime truth. ### Phase 4 — External integrations - add IntegrationOperation; - implement per-system ACL/ports/adapters; - add retry/circuit/resilience policy according to external semantics. ### Phase 5 — Read projections and product UI - consolidate Insights/read projections; - build Case-centered Orgo UI from composable presentation profiles; - preserve standalone + Koali-hosted modes. ## 19. Non-negotiable architectural invariants 1. Orgo stays organization/tenant scoped. 2. Work owns canonical Case/Task mutations. 3. Signal is accepted/persisted before retry-prone orchestration causes duplicate effects. 4. Workflow evaluation stays deterministic and side-effect free. 5. Internal ACID transactions are preferred over internal sagas. 6. External/long-running effects are durable, idempotent and receipt-driven. 7. External state never becomes Orgo Task/Case status by implication. 8. Insights/read models cannot mutate operational state directly. 9. Koali hosting remains optional; Orgo stays standalone-capable. 10. Module dependency rules are enforced in code/CI. ## Completion delivery reference — 2026-09-09 The active implementation and its remaining external-contract boundaries are recorded in `IMPLEMENTATION_STATUS.md`. See `COMPLETION_DECISIONS.md` for durable processes, receipt predicates, Work scopes, identity and evidence semantics; `ARCHITECTURE_TO_CODE.md` for source ownership; `LOCAL_VALIDATION.md` for the final acceptance to run locally. Historical validation results do not validate the completion changes. ================================================================================================ FILE: Docs/Technical-Reference/UI_AND_KOALI_INTEGRATION.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: dc142c599a095d89cd95f60640634fc9f855d5cd47b5293c6b0fd6971a0186ca CONTENT_BYTES: 11959 ================================================================================================ # Orgo — UI Architecture and Koali Integration **Status:** Canonical direction for the Orgo vNext frontend and Koali hosting boundary. **Delivery update:** The active frontend implements shared OrgoApp composition and a code-level hosted entry. Native Koali manifest admission and host execution remain unverified because those contract packages are not supplied. See `IMPLEMENTATION_STATUS.md`. This document defines the intended architecture. The current Orgo web snapshot is smaller than this target and must be aligned incrementally. The UI composition is backed by the same operational model defined in `TARGET_ARCHITECTURE.md`: Signal intake, Case-centered Work, Tasks and Orchestration. ## 1. Ownership invariant Orgo is a proprietary integrated subsystem/application. It owns its operational domain and its business UI. Orgo owns: - Cases, Tasks, Signals and Workflows; - routing, escalation and operational actions; - Orgo tenant rules and business authorization; - Orgo routes and inner navigation; - the Orgo Control Panel, inspectors and commands; - Orgo presentation profiles. Koali owns the outer hosting/composition environment when Orgo is installed there. Koali does not become the owner of Orgo business state, business authorization or UI behavior. Required invariant: ```text Koali --hosts--> Orgo Koali -X-> owns Orgo business/UI Orgo -X-> requires Koali to function ``` Orgo must remain installable/removable as a subsystem and must remain usable standalone. ## 2. Two runtime presentation modes, one Orgo application Orgo supports two presentation modes over the same application code and business APIs: ```text ORGO UI ├── standalone └── hosted by Koali ``` The hosted mode is not a second frontend. It mounts/contributes the Orgo application through the canonical Koali module interface. Conceptual structure: ```text orgo-ui/ app/ routes/ features/ shell/ inspectors/ commands/ presentation/ standalone-entry koali-module-entry ``` ## 3. Koali hosting boundary Koali Spaces already has an outer `GlobalShell`. Orgo must not introduce a second global Koali shell. Canonical relationship: ```text Koali Spaces └── GlobalShell ├── ModuleSelector ├── SharedTopBar ├── ActiveModuleSidebar └── MainPageSurface │ └── Orgo local_module_surface │ └── Orgo application ``` The canonical Koali application route family is `/apps/[moduleId]/...`. Orgo contributes through the installed/admitted module manifest mechanism rather than hard-coding itself into a global product switcher. The Koali integration concepts are the existing Koali concepts: ```text Space └── module_instance └── Module Interface Manifest ├── routes ├── sidebar ├── widgets ├── required capabilities └── surface references ``` Do not create a parallel Koali taxonomy named `Product`, `SurfaceProfile` or `Capability`. For Koali integration, use the canonical concepts such as `module`, `moduleInstance`, `surface`, `capabilityProjection` and `presentationPolicy`. When hosted, Orgo is presented as a `local_module_surface`: a complete owner-managed application surface rendered inside the Koali environment. ## 4. Outer navigation vs inner navigation Two navigation layers are intentional: ```text OUTER — KOALI ModuleSelector Space navigation SharedTopBar context shortcuts ↓ INNER — ORGO My Work Cases Tasks Signals Workflows Routing People Organizations Insights Integrations Audit System ``` The outer shell knows which module is active. Orgo knows how work is performed inside Orgo. Do not merge both layers into one large Koali sidebar. ## 5. Orgo UI composition model The canonical UI principle is not “build the full Control Panel and hide items for smaller interfaces.” It is: ```text shared Orgo UI primitives ↓ routes / capabilities / panels / actions ↓ presentation composition ↓ Orgo presentation profile ``` The full Control Panel is the maximal composition, not the physical parent of every reduced UI. Orgo presentation profiles may include: ```text Full Control Panel Operations My Work Supervisor Intake Workflow Admin Executive Embedded ``` These are internal Orgo UX profiles, not Koali surface categories. A presentation profile may control: - its home route; - navigation groups; - exposed product capabilities; - available actions; - widgets; - search/command scopes; - inspector behavior; - density and other presentation policy. Presentation is not authorization. Backend authorization remains authoritative. ## 6. Authorization boundary Koali may consume non-authoritative capability projections to decide presentation behavior such as: ```text show / hide enable / disable choose a safe route show unavailable ``` An Orgo mutation must still be authorized by Orgo: ```text Koali capability projection ↓ presentation decision ↓ Orgo receives command ↓ Orgo revalidates identity RBAC tenant policy ↓ mutation ``` Do not replace Orgo RBAC with Koali RBAC. Do not assume that a Koali login/session is automatically an authorized Orgo session unless a separate SSO contract explicitly establishes that mapping. ## 7. Case-centered operational UX `Case` is the primary operational workspace. `Task` and `Signal` remain first-class entities and transverse views, but they should not read as three unrelated applications. ```text Signals ───────┐ Signals ───────┼──> Case │ ├── Tasks │ ├── Workflow │ ├── People / ownership │ ├── Evidence / attachments │ ├── Timeline │ └── Audit │ └── contextual evolution ``` A Case workspace should make these relationships visible. Transverse views serve different operational questions: - **Cases:** where are situations and durable contexts? - **Tasks:** what work must be executed? - **Signals:** what is arriving or changing? - **My Work:** what requires the current user's attention? A Signal may enrich an existing Case; it is not only a one-time Case creation trigger. ## 8. Orgo Control Panel The maximal Orgo presentation remains a large operational control panel: ```text ┌──────────────┬──────────────────────────────┬──────────────┐ │ ORGO NAV │ │ INSPECTOR │ │ │ │ │ │ My Work │ │ selected │ │ Cases │ WORKSPACE │ entity │ │ Tasks │ │ │ │ Signals │ │ context │ │ │ │ relations │ │ Workflows │ │ quick actions│ │ Routing │ │ │ │ │ │ │ │ People │ │ │ │ Insights │ │ │ │ Audit │ │ │ └──────────────┴──────────────────────────────┴──────────────┘ ``` The exact inner navigation is presentation-profile dependent. Technical/admin entries such as Integrations, System, Organizations or workflow configuration should not appear to operators unless their Orgo profile and permissions require them. There is no universal `Overview` route. Home is a presentation-profile property, for example: ```text Operations -> Operations Dashboard Supervisor -> Team Overview My Work -> Work Queue Executive -> Situation Overview Admin -> System Overview ``` ## 9. Inspector rule The Inspector is initially an Orgo-owned primitive. Do not modify the Koali `GlobalShell` merely to make the Inspector universal. If multiple modules later need the same contract, promotion into Koali can be considered separately. Use three levels of depth: ```text Row / Card -> summary Inspector -> context -> quick edit -> quick action -> related entities -> deep link Full Page / Workspace -> complex work -> full history -> structured configuration ``` The Inspector must not reproduce an entire full page in a narrow panel. It should provide a deep link to the full workspace when deeper work is required. ## 10. Command system Orgo should have an internal command/action system suitable for fast operational work. A command registry may power buttons, context actions, bulk actions and an Orgo command launcher. Examples: ```text Open case… Create case… Assign task… Escalate… Search signal… Go to workflow… Run action… ``` Koali's `SharedTopBar` may accept module command references through its existing contracts. A global Koali `Ctrl+K` behavior is a separate architecture decision and must not be assumed by Orgo. ## 11. Konnaxion reuse rule Konnaxion is a useful implementation reference for layout mechanics and UI patterns, including sidebar, header, mobile drawer, page shells, navigation ergonomics and dashboard density. Do not use Konnaxion to redefine Koali's global architecture. Correct direction: ```text Konnaxion frame/patterns ↓ selective reuse/adaptation Orgo-owned shell and UI primitives ↓ Orgo application ``` Incorrect direction: ```text Konnaxion ↓ new KoaliShell ↓ Orgo ``` ## 12. Integration with Kristal and other systems UI integration does not change ownership boundaries. Orgo may expose actions/workflows that invoke Kristal or another external system through explicit adapters, operations and receipts. Do not represent external epistemic/platform/civic state as Orgo Task/Case status merely because it is visible in the Orgo Control Panel. The UI should display external state as referenced/provenanced external state and route mutations through the owning system's contract. ## 13. Implementation direction Target organization (names may be adjusted to the actual framework/repository layout): ```text apps/web/src/orgo/ ├── app/ │ ├── OrgoApp │ ├── standalone-entry │ └── koali-module-entry ├── shell/ │ ├── OrgoShell │ ├── OrgoNavigation │ ├── OrgoHeader │ ├── OrgoWorkspace │ └── OrgoInspectorHost ├── presentation/ │ ├── full │ ├── operations │ ├── my-work │ ├── supervisor │ ├── intake │ ├── workflow-admin │ ├── executive │ └── embedded ├── cases/ ├── tasks/ ├── signals/ ├── workflows/ ├── routing/ ├── organization/ ├── insights/ ├── inspectors/ ├── commands/ ├── actions/ └── integration/koali/ ``` Do not force this target directory structure mechanically if the current framework layout has a cleaner equivalent. The architectural boundaries are normative; exact filenames are not. ## 14. Current-state note The current Orgo web snapshot is not yet this application. It contains useful types/screens/hooks but a small effective route tree. Build/runtime repair and core-domain stabilization should precede or accompany the UI composition work. ================================================================================================ FILE: Docs/Technical-Reference/v3/1-Orgo v3 - Database Schema Reference.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 216f9cc8d5b655953ccff79c7a6e6a3b38d76b8b1399ae4e4e738144f4480c2e CONTENT_BYTES: 5611 ================================================================================================ # Orgo v3 — Database Schema Reference ## Authority `apps/api/prisma/schema.prisma` and the applied migrations are the physical schema authority. This document records ownership and the major table/model families rather than duplicating every column. ## 1. Multi-tenancy and identity Core models: ```text Organization OrganizationProfile UserAccount PersonProfile Role Permission RolePermission UserRoleAssignment LoginSession ApiToken ``` `Organization` is the tenant root. Operational records that belong to an organization carry `organization_id`. User and Person remain distinct: ```text UserAccount = login/actor PersonProfile = human subject ``` ## 2. Communication/email ```text EmailAccountConfig RoleInbox EmailThread EmailMessage EmailAttachment EmailIngestionBatch EmailProcessingEvent ``` Email state can generate/link operational work but does not replace Task/Case state. ## 3. Task core ### `Task` Key fields: - `id`; - `organization_id`; - optional `case_id`; - `external_reference`; - `type`, `category`, `subtype`, `label`; - `title`, `description`; - `status`, `priority`, `severity`, `visibility`, `source`; - creator/requester/owner/assignee references; - SLA/deadline/escalation fields; - `metadata`; - timestamps. Related models: ```text TaskAssignment TaskEvent TaskComment ``` These tables provide assignment history, lifecycle/audit events and comments without creating a second Task lifecycle. ## 4. Workflow/routing ```text RoutingRule WorkflowDefinition WorkflowInstance WorkflowTransitionEvent EscalationPolicy EscalationInstance EscalationEvent ``` The DB workflow tables are operational state. Filesystem/YAML workflow rules used by the current engine must be reconciled with these models rather than treated as an unrelated second source of workflow truth. ## 5. Configuration ```text ParameterOverride FeatureFlag LabelDefinition EntityLabel OrganizationProfile ``` Profiles/config tune behavior; they do not redefine core enums. ## 6. Notification, audit, security ```text NotificationTemplate Notification ActivityLog SecurityEvent SystemMetricSnapshot ``` Audit/log state observes operations; it does not become owner of the work object observed. ## 7. Case core ### `Case` Key fields: - `id`; - `organization_id`; - `source_type`, `source_reference`; - `label`; - `title`, `description`; - `status`, `severity`; - `reactivity_time`; - origin vertical/role; - tags/location/metadata; - timestamps. Tasks link to a Case through `tasks.case_id`. ## 8. Maintenance extension ```text MaintenanceAsset MaintenanceTaskLink MaintenanceCalendarSlot ``` The maintenance domain extends canonical Tasks by linking assets/schedule state. The extension must not create a separate canonical Task lifecycle. ## 9. HR extension ```text HrCase HrCaseParticipant HrCaseTaskLink WellbeingCheckin ``` `HrCase.case_id` links the HR domain record to the canonical Case. HR work links back to canonical Tasks. ## 10. Education/groups extension ```text LearningGroup LearningGroupMembership EducationTaskLink ``` Education context links to canonical Tasks through `EducationTaskLink`. ## 11. Offline/sync ```text OfflineNode SyncSession SyncConflict EmailArchiveImportBatch ImportedMessageMapping ``` Offline synchronization must preserve the same tenant, lifecycle, enum and audit invariants as online mutations. ## 12. Insights star schema ```text DimDate DimOrganization DimTask DimCase DimPerson DimLearningGroup FactTask FactCase FactWellbeingCheckin ``` These are analytical projections. They are not the write authority for operational Task/Case state. ## 13. Core enums Physical enums include: ```text OrganizationStatus TaskStatus TaskPriority TaskSeverity Visibility TaskSource TaskCategory CaseStatus CommentVisibility WorkflowInstanceStatus NotificationChannel NotificationStatus TaskEventType TaskEventOrigin HrCaseStatus HrCaseConfidentialityLevel HrCaseParticipantRole MaintenanceCalendarSlotStatus SyncDirection SyncStatus SyncResolutionStrategy ``` Public JSON casing may differ at explicit boundaries, but each enum has one semantic vocabulary. ## 14. Target architecture additions (not yet physical schema authority) The target architecture requires several models/records that are **not present as canonical Prisma models in the supplied snapshot**. They must be introduced by explicit migrations before code/docs may treat them as implemented. ### `Signal` First-class accepted intake/evidence record, organization-scoped and idempotent at retry-prone boundaries. It should be linkable to the Case/Tasks/actions it caused or enriched. ### `WorkflowVersion` Immutable/versioned runtime ruleset linked to `WorkflowDefinition`. `WorkflowInstance` should pin the exact version/hash used. YAML remains import/export/authoring material. ### `OutboxMessage` Durable post-commit message written atomically with a business mutation. Used by the Orgo worker for notifications, integrations, retries and projection work. ### `IntegrationOperation` Orgo-owned record of an external request/result/receipt. External lifecycle status must not be encoded into `Task.status` or `Case.status`. ### Idempotency storage A dedicated record or equivalent unique constraints are required where a stable `(organization, operation/source, idempotency_key)` boundary cannot be enforced directly on the target aggregate. `ExecutionContext` is primarily an application/platform contract and need not be a single database table; correlation/causation/idempotency fields should be persisted on the records that require durable traceability. ================================================================================================ FILE: Docs/Technical-Reference/v3/1-orgo-database-schema-reference.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 1d5d33ee1859e5dbb0ab4349c8118de6358c23a8575400c3495382c382b29cbb CONTENT_BYTES: 47606 ================================================================================================ > **Legacy/reference document.** This file is retained for historical detail and may describe earlier implementation assumptions. For current architecture, use `../TARGET_ARCHITECTURE.md` plus the concise canonical v3 files whose names begin with `1-Orgo`, `2-Orgo`, etc. When this document conflicts with those sources or the physical code/schema authority, it is non-canonical. Preface 1.1 Scope 1.2 Technology & naming assumptions 1.3 Multi‑tenancy conventions 1.4 Default audit columns 1.5 Enum implementation Module 1 – Core Platform & Multi‑Tenancy 2.1 Organization (organizations) 2.2 Organization Profile (organization_profiles) Module 2 – Identity & Access Control 3.1 User Accounts & Person Profiles (user_accounts, person_profiles) 3.2 Roles, Permissions & User Role Assignments (roles, permissions, role_permissions, user_role_assignments) 3.3 Sessions & API Tokens (login_sessions, api_tokens) Module 3 – Communication & Email 4.1 Email Account Configuration (email_account_configs) 4.2 Role Inboxes (role_inboxes) 4.3 Email Threads & Messages (email_threads, email_messages) 4.4 Email Attachments (email_attachments) 4.5 Email Ingestion & Processing Events (email_ingestion_batches, email_processing_events) Module 4 – Task & Workflow Engine 5.1 Tasks, Assignments, Events & Comments (tasks, task_assignments, task_events, task_comments) 5.2 Routing Rules (routing_rules) 5.3 Workflow Definitions & Instances (workflow_definitions, workflow_instances, workflow_transition_events) 5.4 Escalation Policies, Instances & Events (escalation_policies, escalation_instances, escalation_events) Module 5 – Configuration, Parameters & Feature Flags 6.1 Parameter Overrides (parameter_overrides) 6.2 Feature Flags (feature_flags) Module 6 – Labeling & Classification 7.1 Label Definitions (label_definitions) 7.2 Entity Labels (entity_labels) Module 7 – Notifications 8.1 Notification Templates (notification_templates) 8.2 Notifications (notifications) Module 8 – Logging, Audit & Observability 9.1 Activity Logs (activity_logs) 9.2 Security Events (security_events) 9.3 System Metric Snapshots (system_metric_snapshots) Module 9 – Cases (Generic) 10.1 Cases (cases) Module 10 – Domain: Operations & Maintenance 11.1 Maintenance Assets (maintenance_assets) 11.2 Maintenance Task Links (maintenance_task_links) 11.3 Maintenance Calendar Slots (maintenance_calendar_slots) Module 11 – Domain: HR & Wellbeing 12.1 HR Cases & Participants (hr_cases, hr_case_participants) 12.2 HR Case Task Links (hr_case_task_links) 12.3 Wellbeing Check‑Ins (wellbeing_checkins) Module 12 – Domain: Education & Groups 13.1 Learning Groups & Memberships (learning_groups, learning_group_memberships) 13.2 Education Task Links (education_task_links) Module 13 – Offline & Sync 14.1 Offline Nodes & Sync Sessions (offline_nodes, sync_sessions) 14.2 Sync Conflicts (sync_conflicts) 14.3 Email Archive Imports & Message Mappings (email_archive_import_batches, imported_message_mappings) Module 14 – Analytics / Insights Star‑Schema (insights.*) 15.1 Date & Organization Dimensions (insights.dim_dates, insights.dim_organizations) 15.2 Task, Case, Person & Group Dimensions (insights.dim_tasks, insights.dim_cases, insights.dim_persons, insights.dim_learning_groups) 15.3 Fact Tables (Tasks, Cases, Wellbeing Check‑Ins) (insights.fact_tasks, insights.fact_cases, insights.fact_wellbeing_checkins) --- # Orgo v3 – Database Schema Reference (Custom Tables) ## Preface ### Scope This document is the **canonical reference for all custom Orgo v3 database tables**: * It covers both the **operational schema** and the **Insights/analytics star‑schema** used by Orgo v3. * It **excludes**: * Database system/catalog tables. * Migration bookkeeping (e.g. Alembic tables). * Any third‑party auth/session tables we might adopt later. Other documents (e.g. Foundations, Core Services, Domain Modules, Insights / Analytics specs) may describe **how** these tables are populated or queried, but **table names and core columns are defined here** and must not diverge. ### Technology & naming assumptions * **Operational database:** PostgreSQL **15+**. *This document defines the canonical shapes for both the operational schema and the analytics star‑schema. The analytics star‑schema MAY be implemented on PostgreSQL 15+ or mirrored into an external warehouse (e.g., BigQuery, Snowflake); when not on Postgres, the same column shapes and token sets apply with warehouse‑appropriate types.* * **Back‑end stacks (implementation‑neutral spec):** * **Python reference implementation:** Python **3.11.x** + SQLAlchemy 2.x. * **TypeScript/NestJS implementation:** NestJS (TypeScript) + ORM (e.g. TypeORM/Prisma). * This document is **language‑agnostic**: table names, column names, and enum values are canonical and must be respected by **all** backend implementations. * **Table naming:** * Table names: `snake_case` plural, optionally qualified with a schema for analytics (e.g. `insights.fact_tasks`). * Model/class names in examples: `PascalCase`. * Example: `Task` → `tasks`. ### Multi‑tenancy conventions * Every Orgo installation can host many **organizations** (tenants). * **Tenancy key:** `organization_id` referencing `organizations.id`. * Rules: * If a record is **org‑scoped**, it has a **non‑NULL `organization_id`**. * If a record is **global**, `organization_id` is **NULL**. * Some definitional tables (e.g. workflows, labels, templates) can be either: * Global (shared defaults, `organization_id IS NULL`), or * Overridden per organization (`organization_id` filled). ### Default audit columns Unless stated otherwise, **all business tables** have: * `created_at` (timestamptz, NOT NULL, default `now()`) * `updated_at` (timestamptz, NOT NULL, auto‑updated) We don’t repeat these in every “Key columns” list unless there’s something special (like `deleted_at`, `closed_at`, etc.). ### Enum implementation For Orgo v3, all enums listed here are implemented as PostgreSQL ENUM types on the **operational schema** with the exact value sets given in this document (not just free‑text columns). For the **Insights/analytics star‑schema** (`insights.*`), the same token sets are stored as `TEXT` columns containing the canonical values, to decouple the warehouse from OLTP enums (see Module 14 and the Insights config). Key examples: * `organization_status_enum = 'active' | 'suspended' | 'archived'` * `task_status_enum = 'PENDING' | 'IN_PROGRESS' | 'ON_HOLD' | 'COMPLETED' | 'FAILED' | 'ESCALATED' | 'CANCELLED'` * `task_priority_enum = 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'` * `task_severity_enum = 'MINOR' | 'MODERATE' | 'MAJOR' | 'CRITICAL'` * `visibility_enum = 'PUBLIC' | 'INTERNAL' | 'RESTRICTED' | 'ANONYMISED'` * `task_source_enum = 'email' | 'api' | 'manual' | 'sync'` * `notification_channel_enum = 'email' | 'sms' | 'in_app' | 'webhook'` > Historical data where `severity = 'info'` SHALL be treated as `severity = 'MINOR'` on read. > Historical Task/Case `source` values: > > * `ui` → `manual` > * `import` → `sync` > * `insight` → `api` (with extra metadata indicating system‑generated origin) **JSON / API representation:** * API payloads use lower‑case representations, e.g. `"pending"`, `"high"`, `"anonymised"`, but they MUST map 1:1 to the enums above. * For visibility, the canonical stored value is `ANONYMISED`; JSON uses `"anonymised"` (always with an **s**, never `"anonymized"`). --- ## Module 1 – Core Platform & Multi‑Tenancy ### Organization & Profile **Organization → Organization (table: organizations)** Purpose: Represents a tenant using Orgo (company, school, community, team, etc.). Key columns: * `id` (UUID PK) * `slug` (text, unique; short code for URLs/config, e.g. `northside-hospital`) * `display_name` (text; human name) * `legal_name` (text, nullable) * `primary_domain` (text, nullable; email/web domain) * `status` (`organization_status_enum`: `active` | `suspended` | `archived`) * `timezone` (text; IANA TZ, e.g. `"America/New_York"`) * `default_locale` (text; e.g. `"en"`, `"fr-CA"`) **Organization Profile → OrganizationProfile (table: organization_profiles)** Purpose: Stores high‑level behavioural profile for an organization (reactivity, transparency, retention, pattern sensitivity). Profile codes correspond to entries in the profiles YAML (friend_group, hospital, advocacy_group, retail_chain, military_organization, environmental_group, artist_collective, etc.). Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, UNIQUE; one active profile per org) * `profile_code` (text; e.g. `friend_group`, `hospital`, `school_basketball`, `advocacy_group`) * `reactivity_profile` (JSONB; per‑task‑type SLA targets, minutes for `LOW`/`MEDIUM`/`HIGH`/`CRITICAL`) * `transparency_profile` (JSONB; defaults for who can see what) * `pattern_sensitivity_profile` (JSONB; thresholds for insights/alerts) * `retention_profile` (JSONB; log & data retention periods per category) * `version` (integer; increments on profile changes) --- ## Module 2 – Identity & Access Control ### Users & Persons **User Account → UserAccount (table: user_accounts)** Purpose: Login account for a human user within a specific organization. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `email` (text; UNIQUE within organization) * `display_name` (text) * `password_hash` (text, nullable for SSO‑only accounts) * `auth_provider` (enum: `local` | `sso` | `external_only`) * `status` (enum: `active` | `invited` | `disabled`) * `locale` (text; optional user‑level override) * `timezone` (text; optional user‑level override) * `last_login_at` (timestamptz, nullable) **Person Profile → PersonProfile (table: person_profiles)** Purpose: Represents a person tasks are about (players, students, employees, community members) regardless of whether they have an Orgo login. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `linked_user_id` (UUID FK → user_accounts.id, nullable; when this person also has a UserAccount) * `external_reference` (text, nullable; e.g. student ID, employee number) * `full_name` (text) * `date_of_birth` (date, nullable) * `primary_contact_email` (text, nullable) * `primary_contact_phone` (text, nullable) * `confidentiality_level` (enum: `normal` | `sensitive` | `highly_sensitive`; used by higher‑level visibility rules) ### Roles & Permissions **Role → Role (table: roles)** Purpose: Named role within an organization (e.g. `maintenance_coordinator`, `hr_officer`, `coach`, `monk`). Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable for global/system roles) * `code` (text; unique per organization when `organization_id` NOT NULL, e.g. `ops_maintenance_coordinator`) * `display_name` (text) * `description` (text) * `is_system_role` (boolean; true for built‑in, protected roles) **Permission → Permission (table: permissions)** Purpose: Atomic capabilities used across Orgo (e.g. `task.view_sensitive`, `workflow.edit_rules`). Key columns: * `id` (UUID PK) * `code` (text; UNIQUE; stable identifier used in code) * `description` (text) **Role Permission → RolePermission (table: role_permissions)** Purpose: Many‑to‑many linking roles to permissions. Key columns: * `id` (UUID PK) * `role_id` (UUID FK → roles.id) * `permission_id` (UUID FK → permissions.id) * `granted_by_user_id` (UUID FK → user_accounts.id, nullable) * `granted_at` (timestamptz) **User Role Assignment → UserRoleAssignment (table: user_role_assignments)** Purpose: Assigns roles to user accounts, optionally scoped (e.g. specific team or site). Key columns: * `id` (UUID PK) * `user_id` (UUID FK → user_accounts.id) * `role_id` (UUID FK → roles.id) * `organization_id` (UUID FK → organizations.id) * `scope_type` (enum: `global` | `team` | `location` | `unit` | `custom`) * `scope_reference` (text, nullable; semantics depend on `scope_type`) * `assigned_at` (timestamptz) * `revoked_at` (timestamptz, nullable) ### Sessions & API Tokens **Login Session → LoginSession (table: login_sessions)** Purpose: Tracks user login sessions for audit and security. Key columns: * `id` (UUID PK) * `user_id` (UUID FK → user_accounts.id) * `organization_id` (UUID FK → organizations.id) * `ip_address` (inet, nullable) * `user_agent` (text, nullable) * `started_at` (timestamptz) * `ended_at` (timestamptz, nullable) * `termination_reason` (enum: `logout` | `timeout` | `forced` | `unknown`) **API Token → ApiToken (table: api_tokens)** Purpose: Long‑lived tokens for programmatic access (bots, integrations). Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `owner_user_id` (UUID FK → user_accounts.id, nullable) * `label` (text; e.g. “Maintenance monitor bot”) * `token_hash` (text; hashed token, not plaintext) * `scopes` (JSONB; list of permission codes or resource patterns) * `expires_at` (timestamptz, nullable) * `revoked_at` (timestamptz, nullable) * `last_used_at` (timestamptz, nullable) --- ## Module 3 – Communication & Email ### Email Accounts & Role Inboxes **Email Account Configuration → EmailAccountConfig (table: email_account_configs)** Purpose: Connection settings for IMAP/SMTP accounts Orgo uses to read/send email. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `label` (text; e.g. “Main HR mailbox”) * `imap_host` (text), `imap_port` (integer), `imap_use_ssl` (boolean) * `smtp_host` (text), `smtp_port` (integer), `smtp_use_ssl` (boolean) * `username` (text) * `encrypted_password` (text; encrypted at rest) * `polling_interval_seconds` (integer; default polling cadence) * `last_successful_poll_at` (timestamptz, nullable) * `is_active` (boolean) **Role Inbox → RoleInbox (table: role_inboxes)** Purpose: Maps roles to incoming email addresses that should create/route tasks. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `role_id` (UUID FK → roles.id) * `email_account_config_id` (UUID FK → email_account_configs.id) * `display_address` (text; e.g. `maintenance@org.example`) * `is_primary` (boolean; one primary per role) * `accept_anonymous` (boolean; if true, tasks created without a known PersonProfile) ### Messages, Threads, Attachments **Email Thread → EmailThread (table: email_threads)** Purpose: Logical conversation thread; groups related messages and links to primary task. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `external_thread_key` (text; provider thread id or synthetic) * `subject_snapshot` (text; canonical subject) * `primary_task_id` (UUID FK → tasks.id, nullable) * `last_message_at` (timestamptz) **Email Message → EmailMessage (table: email_messages)** Purpose: Normalized metadata and body for individual emails Orgo ingests or sends. Logical use in Core Services follows the EMAIL_MESSAGE model in the Core Services spec; this table is the physical storage. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `email_account_config_id` (UUID FK → email_account_configs.id, nullable) * `thread_id` (UUID FK → email_threads.id, nullable) * `message_id_header` (text, nullable; RFC822 `Message-ID`) * `direction` (enum: `inbound` | `outbound`) * `from_address` (text) * `to_addresses` (text[]; array of RFC822 addresses) * `cc_addresses` (text[], nullable) * `bcc_addresses` (text[], nullable) * `subject` (text) * `received_at` (timestamptz, nullable) * `sent_at` (timestamptz, nullable) * `raw_headers` (text) * `text_body` (text, nullable) * `html_body` (text, nullable; may be truncated; full body can live in blob storage) * `related_task_id` (UUID FK → tasks.id, nullable) * `sensitivity` (enum: `normal` | `sensitive` | `highly_sensitive`) **Email Attachment → EmailAttachment (table: email_attachments)** Purpose: Metadata for email attachments, with content in external storage. Key columns: * `id` (UUID PK) * `email_message_id` (UUID FK → email_messages.id) * `file_name` (text) * `mime_type` (text) * `size_bytes` (bigint) * `storage_key` (text; key/path in object store) * `checksum` (text; e.g. SHA256) ### Email Ingestion **Email Ingestion Batch → EmailIngestionBatch (table: email_ingestion_batches)** Purpose: Tracks each IMAP/POP/Archive poll job for observability and retry. Key columns: * `id` (UUID PK) * `email_account_config_id` (UUID FK → email_account_configs.id) * `started_at` (timestamptz) * `finished_at` (timestamptz, nullable) * `message_count` (integer; messages seen in this batch) * `status` (enum: `running` | `completed` | `failed`) * `error_summary` (text, nullable) **Email Processing Event → EmailProcessingEvent (table: email_processing_events)** Purpose: Logs processing steps for an email: parsed, classified, linked, or dropped. Key columns: * `id` (UUID PK) * `email_message_id` (UUID FK → email_messages.id) * `event_type` (enum: `parsed` | `classification_succeeded` | `classification_failed` | `task_created` | `linked_to_existing_task` | `dropped`) * `details` (JSONB; e.g. classifier scores, matching rules) * `created_at` (timestamptz) --- ## Module 4 – Task & Workflow Engine ### Tasks & Comments **Task → Task (table: tasks)** Purpose: Central unit of work in Orgo; all workflows (maintenance, HR, education, etc.) map to tasks with metadata. The canonical Task field set and enums are locked in the Foundations doc and reused by domain modules and core services. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `case_id` (UUID FK → cases.id, nullable; ties this task to a generic Case) * `type` (text; domain‑level type, e.g. `maintenance`, `hr_case`, `education_support`, `it_support`, `operations`, `generic`) * `category` (enum: `request` | `incident` | `update` | `report` | `distribution`) * `subtype` (text; domain‑specific, e.g. `plumbing`, `harassment`, `attendance`) * `label` (text; canonical information label `..`) * `title` (text) * `description` (text) * `status` (`task_status_enum`: `PENDING` | `IN_PROGRESS` | `ON_HOLD` | `COMPLETED` | `FAILED` | `ESCALATED` | `CANCELLED`) * `priority` (`task_priority_enum`: `LOW` | `MEDIUM` | `HIGH` | `CRITICAL`) * `severity` (`task_severity_enum`: `MINOR` | `MODERATE` | `MAJOR` | `CRITICAL`; **NOT NULL**, default `MINOR` if unspecified) * `visibility` (`visibility_enum`: `PUBLIC` | `INTERNAL` | `RESTRICTED` | `ANONYMISED`) * `source` (`task_source_enum`: `email` | `api` | `manual` | `sync`) * `created_by_user_id` (UUID FK → user_accounts.id, nullable) * `requester_person_id` (UUID FK → person_profiles.id, nullable) * `owner_role_id` (UUID FK → roles.id, nullable; primary owning role) * `owner_user_id` (UUID FK → user_accounts.id, nullable; direct owner) * `assignee_role` (text, nullable; denormalized role identifier such as `"Ops.Maintenance"`, aligned with the label system) * `reactivity_time` (interval, nullable; SLA/expected response time) * `reactivity_deadline_at` (timestamptz, nullable; typically `created_at + reactivity_time` under the active org profile) * `due_at` (timestamptz, nullable) * `escalation_level` (integer, NOT NULL, default 0; 0 = no escalation, 1+ = escalation depth) * `closed_at` (timestamptz, nullable) * `metadata` (JSONB; domain‑specific fields, e.g. asset_id, group_id, location) > `owner_role_id` / `owner_user_id` are normalized FKs; `assignee_role` is a denormalized label string used for routing/label semantics and cross‑system references. > Confidentiality is handled via **visibility + org/person/case confidentiality**, not a task‑local `confidentiality_level` field. **Task Assignment → TaskAssignment (table: task_assignments)** Purpose: History of which roles/users have been assigned to a task (primary & secondary). Key columns: * `id` (UUID PK) * `task_id` (UUID FK → tasks.id) * `assigned_role_id` (UUID FK → roles.id, nullable) * `assigned_user_id` (UUID FK → user_accounts.id, nullable) * `is_primary` (boolean) * `assigned_at` (timestamptz) * `unassigned_at` (timestamptz, nullable) * `assignment_reason` (text, nullable) **Task Event → TaskEvent (table: task_events)** Purpose: Append‑only event log for task lifecycle, used for audit and analytics. Key columns: * `id` (UUID PK) * `task_id` (UUID FK → tasks.id) * `organization_id` (UUID FK → organizations.id) * `event_type` (enum: `created` | `status_changed` | `priority_changed` | `ownership_changed` | `comment_added` | `email_linked` | `escalated` | `deadline_updated` | `metadata_updated`) * `old_value` (JSONB, nullable) * `new_value` (JSONB, nullable) * `actor_user_id` (UUID FK → user_accounts.id, nullable) * `actor_role_id` (UUID FK → roles.id, nullable) * `origin` (enum: `ui` | `api` | `email` | `system_rule`) * `created_at` (timestamptz) **Task Comment → TaskComment (table: task_comments)** Purpose: Comment/discussion entries attached to tasks, with visibility control. Key columns: * `id` (UUID PK) * `task_id` (UUID FK → tasks.id) * `author_user_id` (UUID FK → user_accounts.id, nullable for system notes) * `visibility` (enum: `internal_only` | `requester_visible` | `org_wide`) * `body` (text) > `TaskComment.visibility` is a **comment‑level audience flag**, distinct from the global `visibility_enum` used on Tasks/Cases. ### Routing Rules **Routing Rule → RoutingRule (table: routing_rules)** Purpose: Declarative rules to decide **who** initially owns new tasks (by role or user) based on type/category/labels. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable for global defaults) * `name` (text; human label, e.g. “Default HR sensitive complaints routing”) * `task_type` (text, nullable; e.g. `maintenance`, `hr_case`) * `task_category` (enum: `request` | `incident` | `update` | `report` | `distribution`, nullable) * `label_codes` (text[]; optional required labels, e.g. `['anonymous']`) * `priority_min` (`task_priority_enum`, nullable) * `target_role_id` (UUID FK → roles.id, nullable) * `target_user_id` (UUID FK → user_accounts.id, nullable) * `is_fallback` (boolean; used when no more specific rule matches) * `weight` (integer; for tie‑breaking between matching rules) ### Workflow Definitions & Instances **Workflow Definition → WorkflowDefinition (table: workflow_definitions)** Purpose: Canonical definition of a workflow (states, transitions, guards) stored as JSON, optionally org‑specific. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable; NULL = global default) * `code` (text; UNIQUE within org or globally, e.g. `maintenance_default`, `hr_sensitive_case`) * `name` (text) * `description` (text) * `definition_blob` (JSONB; normalized workflow spec: states, transitions, actions) * `is_active` (boolean) * `version` (integer) **Workflow Instance → WorkflowInstance (table: workflow_instances)** Purpose: Runtime instance of a workflow bound to a task. Key columns: * `id` (UUID PK) * `workflow_definition_id` (UUID FK → workflow_definitions.id) * `task_id` (UUID FK → tasks.id) * `organization_id` (UUID FK → organizations.id) * `current_state` (text; key from definition) * `status` (enum: `running` | `completed` | `cancelled`) * `started_at` (timestamptz) * `finished_at` (timestamptz, nullable) **Workflow Transition Event → WorkflowTransitionEvent (table: workflow_transition_events)** Purpose: Logs transitions between workflow states, including who triggered them. Key columns: * `id` (UUID PK) * `workflow_instance_id` (UUID FK → workflow_instances.id) * `task_id` (UUID FK → tasks.id) * `from_state` (text, nullable when first state) * `to_state` (text) * `trigger` (text; e.g. `submit`, `approve`, `close`) * `actor_user_id` (UUID FK → user_accounts.id, nullable) * `actor_role_id` (UUID FK → roles.id, nullable) * `reason` (text, nullable) * `occurred_at` (timestamptz) ### Escalation & SLA **Escalation Policy → EscalationPolicy (table: escalation_policies)** Purpose: Multi‑step escalation plans for certain task types/categories. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable for global policies) * `task_type` (text, nullable) * `category` (enum: `request` | `incident` | `update` | `report` | `distribution`, nullable) * `policy_code` (text; e.g. `standard_hr_sensitive`, unique per org) * `definition` (JSONB; steps with timing + target roles/users/channels) * `is_default` (boolean) * `version` (integer) **Escalation Instance → EscalationInstance (table: escalation_instances)** Purpose: Runtime execution of an escalation policy for a particular task. Key columns: * `id` (UUID PK) * `task_id` (UUID FK → tasks.id) * `escalation_policy_id` (UUID FK → escalation_policies.id) * `current_step_index` (integer) * `status` (enum: `idle` | `scheduled` | `in_progress` | `completed` | `cancelled`) * `next_fire_at` (timestamptz, nullable) * `started_at` (timestamptz) * `completed_at` (timestamptz, nullable) **Escalation Event → EscalationEvent (table: escalation_events)** Purpose: Logs each concrete escalation action taken for a task. Key columns: * `id` (UUID PK) * `escalation_instance_id` (UUID FK → escalation_instances.id) * `task_id` (UUID FK → tasks.id) * `step_index` (integer) * `action_type` (enum: `notify_role` | `notify_user` | `auto_reassign` | `auto_close` | `raise_severity`) * `action_payload` (JSONB; details: which role/user, which channel) * `executed_at` (timestamptz) * `success` (boolean) * `error_message` (text, nullable) --- ## Module 5 – Configuration, Parameters & Feature Flags **Parameter Override → ParameterOverride (table: parameter_overrides)** Purpose: Physical storage of configuration knobs (parameters) per org, aligned with the Global Parameter Reference. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable for global defaults) * `module_code` (text; e.g. `core`, `maintenance`, `hr`, `education`, `insights`) * `parameter_key` (text; stable identifier, e.g. `reactivity.hr.critical_sla_minutes`) * `value` (JSONB; typed via param spec: number/string/enum/object) * `source` (enum: `default` | `org_override` | `profile` | `runtime`) * `effective_from` (timestamptz) **Feature Flag → FeatureFlag (table: feature_flags)** Purpose: Toggles to roll out or restrict features per organization. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable for global flags) * `code` (text; e.g. `insights_cyclic_reviews_v2`) * `description` (text) * `enabled` (boolean) * `rollout_strategy` (JSONB; e.g. percentage, subset of roles) * `enabled_from` (timestamptz, nullable) * `disabled_at` (timestamptz, nullable) --- ## Module 6 – Labeling & Classification ### Canonical labels vs classification tags * `tasks.label` and `cases.label` store the **canonical information label** of the form `..`, as defined in the cross‑document Orgo v3 semantics. * The `label_definitions` and `entity_labels` tables are used for **additional classification tags** (e.g. `self_harm_risk`, `equipment_failure`, `conflict`) that are attached to tasks, people, groups, and cases. * Canonical labels are 1‑per‑entity (Task/Case); classification tags are 0‑to‑many per entity. **Label Definition → LabelDefinition (table: label_definitions)** Purpose: Standardized labels used for classification/pattern detection. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable for global labels) * `code` (text; unique per org/global, e.g. `anonymous`, `equipment_failure`) * `display_name` (text) * `description` (text) * `category` (text; e.g. `risk`, `topic`, `visibility`) * `color_hint` (text, nullable; hex or name for UI) **Entity Label → EntityLabel (table: entity_labels)** Purpose: Attaches labels to different entities (tasks, people, groups, cases) in a uniform way. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `label_id` (UUID FK → label_definitions.id) * `entity_type` (text; e.g. `task`, `person`, `learning_group`, `case`, `hr_case`) * `entity_id` (UUID; ID in the corresponding table) * `applied_by_user_id` (UUID FK → user_accounts.id, nullable) * `applied_at` (timestamptz) --- ## Module 7 – Notifications **Notification Template → NotificationTemplate (table: notification_templates)** Purpose: Templates for notifications per org and channel (subject/body or payload format). Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable for global templates) * `code` (text; unique per org, e.g. `task_created_requester`, `task_escalated_owner`) * `channel` (`notification_channel_enum`: `email` | `sms` | `in_app` | `webhook`) * `subject_template` (text, nullable; email‑only) * `body_template` (text; text or JSON payload template) * `is_active` (boolean) * `version` (integer) **Notification → Notification (table: notifications)** Purpose: Individual notification instances queued/sent to users or external targets. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `channel` (`notification_channel_enum`: `email` | `sms` | `in_app` | `webhook`) * `recipient_user_id` (UUID FK → user_accounts.id, nullable) * `recipient_address` (text, nullable; email/phone/webhook URL/device token) * `template_id` (UUID FK → notification_templates.id, nullable if custom payload) * `payload` (JSONB; merged data ready for the channel) * `status` (enum: `queued` | `sent` | `failed` | `cancelled`) * `related_task_id` (UUID FK → tasks.id, nullable) * `queued_at` (timestamptz) * `sent_at` (timestamptz, nullable) * `failed_at` (timestamptz, nullable) * `error_message` (text, nullable) + Channel values in both tables are stored as lower-case tokens and map 1:1 to the global `NOTIFICATION_CHANNEL` enum (`EMAIL`, `SMS`, `IN_APP`, `WEBHOOK`) used in configs and services. Mobile push, if implemented, MUST be modelled via `IN_APP` plus client-side delivery; a distinct `PUSH` channel is not supported. --- ## Module 8 – Logging, Audit & Observability **Activity Log → ActivityLog (table: activity_logs)** Purpose: Generic, non‑security activity log for user/system actions (for audit & insights). Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `user_id` (UUID FK → user_accounts.id, nullable) * `session_id` (UUID FK → login_sessions.id, nullable) * `actor_type` (enum: `user` | `system`) * `action` (text; e.g. `task_viewed`, `config_updated`, `report_run`) * `target_type` (text; e.g. `task`, `workflow_definition`, `person`) * `target_id` (UUID, nullable) * `details` (JSONB) **Security Event → SecurityEvent (table: security_events)** Purpose: High‑importance security events (failed logins, permission changes, suspicious exports). Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable for system‑wide events) * `user_id` (UUID FK → user_accounts.id, nullable) * `event_type` (enum: `failed_login` | `permission_escalation` | `api_abuse` | `data_export` | `config_change`) * `ip_address` (inet, nullable) * `user_agent` (text, nullable) * `details` (JSONB) * `severity` (enum: `low` | `medium` | `high` | `critical`) **System Metric Snapshot → SystemMetricSnapshot (table: system_metric_snapshots)** Purpose: Periodic snapshots of aggregated metrics for long‑term trends at low cardinality. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id, nullable) * `period_start` (timestamptz) * `period_end` (timestamptz) * `metrics` (JSONB; e.g. `tasks_created`, `escalations_triggered`, `avg_response_time_minutes`) --- ## Module 9 – Cases (Generic) **Case → Case (table: cases)** Purpose: Generic case container that groups tasks, patterns, and context across domains (HR, maintenance incidents, education support, advocacy, etc.). JSON contracts and lifecycle semantics are defined in the Cyclic Overview / JSON doc; this table is the physical backing. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `source_type` (enum: `email` | `api` | `manual` | `sync`; same semantics as `tasks.source`) * `source_reference` (text, nullable; external id or URI) * `label` (text; canonical information label `..`) * `title` (text) * `description` (text) * `status` (enum: `open` | `in_progress` | `resolved` | `archived`; canonical case lifecycle) * `severity` (`task_severity_enum`: `MINOR` | `MODERATE` | `MAJOR` | `CRITICAL`) * `reactivity_time` (interval, nullable; expected responsiveness window for the case) * `origin_vertical_level` (integer; e.g. 1, 10, 100, 1000) * `origin_role` (text; e.g. `"Ops.Maintenance"`, `"HR.CaseOfficer"`) * `tags` (text[]; high‑level tags, e.g. `['harassment','classroom']`) * `location` (JSONB; structure holding physical/organizational location info) * `metadata` (JSONB; includes `pattern_sensitivity`, `review_frequency`, `notification_scope`, `visibility`, `escalation_path[]`, `profile_id`, and other case‑level settings) > Links from cases to tasks and related cases are represented via join tables and domain‑specific link tables (e.g. `tasks.case_id`, `hr_case_task_links`, and optional generic `case_case_links` if introduced later). > Historical `source_type` values such as `email_thread`, `import`, `insight` SHOULD be mapped during migration to `email`, `sync`, or `api` respectively. --- ## Module 10 – Domain: Operations & Maintenance **Maintenance Asset → MaintenanceAsset (table: maintenance_assets)** Purpose: Assets that can have maintenance tasks (buildings, rooms, vehicles, equipment). Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `code` (text; unique per org, e.g. `BLDG_A_F2_R210`) * `name` (text) * `category` (text; e.g. `building` | `room` | `vehicle` | `equipment`) * `location_description` (text, nullable) * `metadata` (JSONB; vendor, serial, capacity, etc.) * `is_active` (boolean) **Maintenance Task Link → MaintenanceTaskLink (table: maintenance_task_links)** Purpose: Connects generic tasks to maintenance context (asset and optional external work order). Key columns: * `id` (UUID PK) * `task_id` (UUID FK → tasks.id) * `asset_id` (UUID FK → maintenance_assets.id) * `work_order_reference` (text, nullable; external CMMS id) * `priority_override` (`task_priority_enum`, nullable) **Maintenance Calendar Slot → MaintenanceCalendarSlot (table: maintenance_calendar_slots)** Purpose: Scheduled work slots for maintenance tasks (for planning, scheduling, and pattern analysis). Key columns: * `id` (UUID PK) * `task_id` (UUID FK → tasks.id) * `assigned_user_id` (UUID FK → user_accounts.id, nullable) * `start_at` (timestamptz) * `end_at` (timestamptz) * `status` (enum: `planned` | `in_progress` | `completed` | `cancelled`) --- ## Module 11 – Domain: HR & Wellbeing **HR Case → HrCase (table: hr_cases)** Purpose: HR‑specific extension of a generic Case for sensitive matters (harassment, conflict, performance, etc.). Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `case_id` (UUID FK → cases.id, UNIQUE; 1‑to‑1 refinement of a generic Case) * `case_code` (text; unique per org, e.g. `HR-2025-0043`) * `title` (text) *(usually mirrors `cases.title`, but HR can override or anonymise)* * `description` (text) *(HR‑specific narrative; may be more detailed or more anonymised than generic `cases.description`)* * `status` (enum: `open` | `under_review` | `resolved` | `dismissed`; HR pipeline state, distinct from generic `cases.status`) * `confidentiality_level` (enum: `sensitive` | `highly_sensitive`; drives stricter visibility and handling rules) * `case_owner_role_id` (UUID FK → roles.id) * `case_owner_user_id` (UUID FK → user_accounts.id, nullable) * `primary_task_id` (UUID FK → tasks.id, nullable) * `opened_at` (timestamptz) * `closed_at` (timestamptz, nullable) **HR Case Participant → HrCaseParticipant (table: hr_case_participants)** Purpose: People involved in an HR case (complainant, respondent, witnesses, advocates). Key columns: * `id` (UUID PK) * `hr_case_id` (UUID FK → hr_cases.id) * `person_id` (UUID FK → person_profiles.id) * `role_in_case` (enum: `complainant` | `respondent` | `witness` | `advocate` | `other`) * `notes` (text, nullable) **HR Case Task Link → HrCaseTaskLink (table: hr_case_task_links)** Purpose: Links generic tasks (meetings, investigations, communications) to an HR case. Key columns: * `id` (UUID PK) * `hr_case_id` (UUID FK → hr_cases.id) * `task_id` (UUID FK → tasks.id) * `link_type` (text; e.g. `investigation`, `communication`, `followup`, `support`) **Wellbeing Check‑In → WellbeingCheckin (table: wellbeing_checkins)** Purpose: Structured wellbeing check‑ins (survey or manual) tied to people/groups for early risk detection. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `person_id` (UUID FK → person_profiles.id, nullable for anonymous) * `submitted_by_user_id` (UUID FK → user_accounts.id, nullable) * `context` (text; e.g. `basketball_team`, `residence`, `study_group`) * `score` (integer; e.g. 1–10) * `tags` (text[]; e.g. `['stress', 'sleep']`) * `notes` (text, nullable) * `related_task_id` (UUID FK → tasks.id, nullable) --- ## Module 12 – Domain: Education & Groups **Learning Group → LearningGroup (table: learning_groups)** Purpose: Represents a class/team/group of learners (school class, basketball team, study group). Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `code` (text; unique per org, e.g. `CLASS_6A`, `BASKETBALL_U15`) * `name` (text) * `description` (text, nullable) * `category` (text; e.g. `school_class` | `sports_team` | `study_circle`) * `advisor_role_id` (UUID FK → roles.id, nullable) **Learning Group Membership → LearningGroupMembership (table: learning_group_memberships)** Purpose: Links people to learning groups with roles (student, player, coach, parent). Key columns: * `id` (UUID PK) * `learning_group_id` (UUID FK → learning_groups.id) * `person_id` (UUID FK → person_profiles.id) * `role` (enum: `student` | `player` | `parent` | `coach` | `teacher` | `mentor`) * `joined_at` (timestamptz) * `left_at` (timestamptz, nullable) **Education Task Link → EducationTaskLink (table: education_task_links)** Purpose: Associates tasks with educational context (groups, individuals, education‑related events). Key columns: * `id` (UUID PK) * `task_id` (UUID FK → tasks.id) * `learning_group_id` (UUID FK → learning_groups.id, nullable) * `person_id` (UUID FK → person_profiles.id, nullable) * `context_note` (text, nullable; e.g. `attendance`, `performance`, `conflict`) --- ## Module 13 – Offline & Sync **Offline Node → OfflineNode (table: offline_nodes)** Purpose: Represents a node/device that can operate offline (SQLite) and sync with central Orgo. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `node_identifier` (text; unique, e.g. hostname + install id) * `description` (text, nullable) * `status` (enum: `active` | `inactive` | `retired`) * `last_sync_at` (timestamptz, nullable) **Sync Session → SyncSession (table: sync_sessions)** Purpose: Tracks each synchronization session between an offline node and central Postgres. Key columns: * `id` (UUID PK) * `offline_node_id` (UUID FK → offline_nodes.id) * `direction` (enum: `upload` | `download` | `bidirectional`) * `started_at` (timestamptz) * `finished_at` (timestamptz, nullable) * `status` (enum: `running` | `completed` | `failed`) * `summary` (JSONB; counts of records created/updated/deleted) * `error_message` (text, nullable) **Sync Conflict → SyncConflict (table: sync_conflicts)** Purpose: Conflicts discovered during sync (e.g. concurrent edits); used for manual or automated resolution. Key columns: * `id` (UUID PK) * `sync_session_id` (UUID FK → sync_sessions.id) * `entity_type` (text; e.g. `task`, `task_event`, `person_profile`) * `entity_id` (UUID) * `server_version` (JSONB; snapshot before resolution) * `client_version` (JSONB; snapshot from offline node) * `resolution_strategy` (enum: `server_wins` | `client_wins` | `manual_review` | `merged`) * `resolved` (boolean) * `resolved_at` (timestamptz, nullable) * `resolved_by_user_id` (UUID FK → user_accounts.id, nullable) **Email Archive Import Batch → EmailArchiveImportBatch (table: email_archive_import_batches)** Purpose: Tracks imports of offline email archives (.pst/.mbox) into Orgo. Key columns: * `id` (UUID PK) * `organization_id` (UUID FK → organizations.id) * `source_type` (enum: `pst` | `mbox` | `eml_folder`) * `source_path` (text; path/URI to archive) * `started_at` (timestamptz) * `finished_at` (timestamptz, nullable) * `status` (enum: `running` | `completed` | `failed`) * `messages_imported` (integer) * `error_summary` (text, nullable) **Imported Message Mapping → ImportedMessageMapping (table: imported_message_mappings)** Purpose: Maps original archive message identifiers to Orgo `email_messages` IDs. Key columns: * `id` (UUID PK) * `email_archive_import_batch_id` (UUID FK → email_archive_import_batches.id) * `external_message_identifier` (text; e.g. PST entry ID) * `email_message_id` (UUID FK → email_messages.id) --- ## Module 14 – Analytics / Insights Star‑Schema All analytics tables live in the **`insights` schema** of the primary PostgreSQL database (or a dedicated analytics database with the same schema names). This module defines the **canonical fact and dimension tables** used by the Insights layer; configuration and retention are defined in the Insights Module Config. In line with the Insights config, **enum‑like fields in this schema are stored as `TEXT` columns** whose values are the canonical enum tokens from the operational schema (`TASK_STATUS`, `TASK_PRIORITY`, `TASK_SEVERITY`, `VISIBILITY`, etc.). They are not Postgres ENUMs in the warehouse. ### Dimensions **Analytics Date Dimension → DimDate (table: insights.dim_dates)** Purpose: Calendar/date dimension used for grouping facts by day. Key columns: * `date_key` (date PK; e.g. `2025-03-14`) * `year` (integer) * `quarter` (integer; 1–4) * `month` (integer; 1–12) * `month_name` (text) * `week_of_year` (integer) * `day_of_week` (integer; 1=Monday–7=Sunday) * `day_name` (text) * `is_weekend` (boolean) **Analytics Organization Dimension → DimOrganization (table: insights.dim_organizations)** Purpose: Organization attributes used in reports. Key columns: * `organization_id` (UUID PK; FK → organizations.id) * `slug` (text) * `display_name` (text) * `org_type` (text; optional, e.g. `hospital`, `school`, `club`) * `timezone` (text) * `active_from` (date) * `active_to` (date, nullable) **Analytics Task Dimension → DimTask (table: insights.dim_tasks)** Purpose: Denormalized view of tasks for reporting (slowly changing dimension). Key columns: * `task_id` (UUID PK; FK → tasks.id) * `organization_id` (UUID FK → organizations.id) * `case_id` (UUID FK → cases.id, nullable) * `label` (text; canonical label) * `type` (text) * `category` (text) * `subtype` (text, nullable) * `priority` (text; one of `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`) * `severity` (text; one of `MINOR`, `MODERATE`, `MAJOR`, `CRITICAL`) * `visibility` (text; one of `PUBLIC`, `INTERNAL`, `RESTRICTED`, `ANONYMISED`) * `source` (text; one of `email`, `api`, `manual`, `sync`) * `assignee_role` (text, nullable) * `created_at` (timestamptz) * `closed_at` (timestamptz, nullable) * `current_status` (text; one of `PENDING`, `IN_PROGRESS`, `ON_HOLD`, `COMPLETED`, `FAILED`, `ESCALATED`, `CANCELLED`) **Analytics Case Dimension → DimCase (table: insights.dim_cases)** Purpose: Denormalized view of cases for reporting. Key columns: * `case_id` (UUID PK; FK → cases.id) * `organization_id` (UUID FK → organizations.id) * `label` (text) * `title` (text) * `status` (text; one of `open`, `in_progress`, `resolved`, `archived`) * `severity` (text; one of `MINOR`, `MODERATE`, `MAJOR`, `CRITICAL`) * `origin_vertical_level` (integer) * `origin_role` (text) * `opened_at` (timestamptz) * `closed_at` (timestamptz, nullable) **Analytics Person Dimension → DimPerson (table: insights.dim_persons)** Purpose: Basic person attributes for reporting on individuals. Key columns: * `person_id` (UUID PK; FK → person_profiles.id) * `organization_id` (UUID FK → organizations.id) * `full_name` (text) * `external_reference` (text, nullable) * `confidentiality_level` (enum: `normal` | `sensitive` | `highly_sensitive`) **Analytics Group Dimension → DimLearningGroup (table: insights.dim_learning_groups)** Purpose: Group attributes (class/team/etc.) used in Insights. Key columns: * `learning_group_id` (UUID PK; FK → learning_groups.id) * `organization_id` (UUID FK → organizations.id) * `code` (text) * `name` (text) * `category` (text) ### Facts **Task Fact → FactTask (table: insights.fact_tasks)** Purpose: One row per task capturing core lifecycle metrics for reporting. Key columns: * `id` (bigserial PK) * `task_id` (UUID FK → tasks.id) * `organization_id` (UUID FK → organizations.id) * `created_date_key` (date FK → insights.dim_dates.date_key) * `closed_date_key` (date FK → insights.dim_dates.date_key, nullable) * `current_status` (text; one of `PENDING`, `IN_PROGRESS`, `ON_HOLD`, `COMPLETED`, `FAILED`, `ESCALATED`, `CANCELLED`) * `priority` (text; one of `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`) * `severity` (text; one of `MINOR`, `MODERATE`, `MAJOR`, `CRITICAL`) * `source` (text; one of `email`, `api`, `manual`, `sync`) * `time_to_first_response_seconds` (bigint, nullable) * `time_to_completion_seconds` (bigint, nullable) * `escalation_count` (integer, default 0) * `comment_count` (integer, default 0) **Case Fact → FactCase (table: insights.fact_cases)** Purpose: One row per case with lifecycle metrics and link counts. Key columns: * `id` (bigserial PK) * `case_id` (UUID FK → cases.id) * `organization_id` (UUID FK → organizations.id) * `opened_date_key` (date FK → insights.dim_dates.date_key) * `closed_date_key` (date FK → insights.dim_dates.date_key, nullable) * `status` (text; one of `open`, `in_progress`, `resolved`, `archived`) * `severity` (text; one of `MINOR`, `MODERATE`, `MAJOR`, `CRITICAL`) * `linked_task_count` (integer, default 0) * `escalation_count` (integer, default 0) * `review_count` (integer, default 0) **Wellbeing Check‑In Fact → FactWellbeingCheckin (table: insights.fact_wellbeing_checkins)** Purpose: One row per wellbeing check‑in, tied to person/group and time. Key columns: * `id` (bigserial PK) * `checkin_id` (UUID FK → wellbeing_checkins.id) * `organization_id` (UUID FK → organizations.id) * `person_id` (UUID FK → person_profiles.id, nullable) * `learning_group_id` (UUID FK → learning_groups.id, nullable) * `date_key` (date FK → insights.dim_dates.date_key) * `score` (integer) * `tags` (text[]) * `related_case_id` (UUID FK → cases.id, nullable) * `related_task_id` (UUID FK → tasks.id, nullable) ================================================================================================ FILE: Docs/Technical-Reference/v3/2-Orgo v3 - Architecture and Invariants.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 32fb353b996b3127d47b1c506182aef0d9b7ea36179d2bbb880db4997570d0f8 CONTENT_BYTES: 8752 ================================================================================================ # Orgo v3 — Architecture and Invariants **Status:** Canonical architectural summary. For the complete target design and migration sequence, see `../TARGET_ARCHITECTURE.md`. ## 1. Identity Orgo is a multi-tenant workflow and operational coordination system. Its job is to turn accepted Signals and existing operational state into governed, auditable Work. ```text input/evidence ↓ Intake / Signal ↓ Orchestration evaluation ↓ Work = Cases + Tasks ↓ assign / execute / escalate / review ↓ events / receipts / projections ``` ## 2. Primary architecture Orgo evolves as a **modular monolith**, not as a Task/Case/Workflow microservice mesh. ```text Orgo │ ┌─────────────────┼──────────────────┐ │ │ │ Intake Work Orchestration Signals Cases + Tasks Workflow adapters assignments Routing normalize comments Escalation │ work events Actions └─────────────────┼──────────────────┘ │ Domain events + Outbox │ ┌───────────┼────────────┐ │ │ │ Communications Integrations Insights ``` Cross-cutting platform capabilities include tenancy, identity/RBAC, ExecutionContext, persistence/transactions, configuration, idempotency, audit and observability. ## 3. Work is the central operational bounded context `Work` owns canonical Case/Task mutations and the evidence directly attached to those lifecycles. ```text Work ├── Case ├── Task ├── Assignment ├── Comment └── Work Event ``` `Work` is an ownership boundary, not a replacement table. ## 4. Task is the executable unit of work Task is defined once and reused everywhere. Domain modules may add domain metadata or extension rows but they do not create competing status/priority/severity/visibility systems for canonical work. ## 5. Case is durable situation/context Case groups related work, Signals and operational context over time. It is the primary operational workspace in the target UX. A Case can hold several Tasks and may accumulate several Signals. It can reference an external subject/object without becoming that external object's owner. ## 6. Signal is a first-class accepted input A Signal may originate from: - email; - API/UI input; - webhook/external integration; - system/timer event; - offline/sync replay. The target flow is: ```text source input → inbound adapter → normalization → idempotency/deduplication → persist Signal → orchestration → explicit Case/Task/action effects ``` **Current-state note:** the supplied Prisma snapshot does not yet contain the canonical persisted Signal model; adding it is part of the migration plan. ## 7. Multi-tenancy and ExecutionContext Every operational access is scoped to an Organization. Protected entry paths resolve a common execution context before application logic: ```text organization actor permissions/authorization reference correlation_id causation_id idempotency_key when applicable source ``` Tenant rules: - organization identity is resolved before sensitive access; - data queries include organization scope; - cross-organization IDs do not bypass scope; - a body/header organization ID is validated against authenticated/authorized context; - analytics and exports preserve organization isolation. ## 8. Workflow Engine stays deterministic and pure The Workflow Engine resolves decisions: ```text WorkflowContext → version-pinned rules → ordered ResolvedWorkflowActions ``` It does not directly absorb all side effects. An Action Executor/Dispatcher applies resolved actions through Work, Communications or integration ports. Simulation uses the same evaluator and persists nothing. ## 9. Workflow runtime truth is persisted/versioned Target relationship: ```text WorkflowDefinition └── WorkflowVersion └── WorkflowInstance pins exact version/hash ``` YAML/filesystem rules remain valid as authoring/import/export/seed artifacts, but they must not remain an unrelated second runtime source of truth. ## 10. Internal actions vs durable external actions Internal actions such as Case/Task creation or assignment normally execute synchronously through owner services and ACID transactions. External or long-running effects use a durable post-commit boundary: ```text business transaction + OutboxMessage → commit → Orgo worker → adapter → receipt/result ``` External operation state is tracked separately through `IntegrationOperation`; it must not be encoded implicitly into Task or Case status. ## 11. Events are typed by purpose Keep distinct: - **domain events** — business facts such as TaskAssigned or CaseResolved; - **audit/security events** — actor/compliance/security evidence; - **integration messages** — durable cross-boundary requests/results. Orgo is state-oriented and does not use Event Sourcing as the canonical persistence model. ## 12. Labels and profiles Labels support routing/classification but do not replace authorization. Broadcast bases `10`, `100`, `1000` are informational by default. Organization profiles tune defaults such as SLA/reactivity, transparency, pattern sensitivity, retention and automation. Profile defaults flow through owner services; they do not fork the schema. ## 13. Domain modules Domain modules are extensions around Work: ```text domain request → domain validation/context → Work public API → canonical Case/Task → domain extension/link rows ``` A domain module may be substantial in business logic, but it does not own a parallel work engine and does not mutate raw Task/Case persistence directly. ## 14. Insights uses light CQRS/read projections Insights is read/analysis oriented. Operational state remains authoritative. Read projections may support My Work, Supervisor workload, dashboards and analytical reporting. A separate warehouse/ORM/broker is an implementation option, not an invariant. Pattern detection becomes operational only by re-entering Work through explicit Case/Task actions. ## 15. External systems use ports + Anti-Corruption Layers Konnaxion, Kristal, SemantiK Architect and kOA remain independent owners of their domains. Each integration should have an explicit port/adapter/mapper boundary. External provider/domain types must not leak into Orgo core models. ## 16. Runtime shape Orgo may run multiple processes while remaining one modular monolith/release: ```text orgo-web orgo-api orgo-worker postgres ``` The worker handles outbox processing, retries, scheduled work, integration operations and projection updates. A separate message broker is not required initially. ## 17. Resilience and observability Apply timeout, bounded retry, exponential backoff/jitter, circuit breaker, concurrency limits and DLQ/manual redrive where external/asynchronous boundaries justify them. Graceful degradation must preserve semantics; a required external validation cannot silently become approval. Propagate structured correlation/causation and entity IDs through logs, metrics and traces. Distinguish liveness and readiness. ## 18. UI ownership and presentation Orgo owns its business UI and inner navigation. The frontend is composed from shared Orgo primitives, routes, actions and panels into internal presentation profiles such as Operations, My Work, Supervisor, Intake, Workflow Admin, Executive and Embedded. The maximal Control Panel is one composition, not the physical parent of every smaller surface. `Case` is the primary operational workspace; Task and Signal remain first-class transverse views. ## 19. Koali hosting invariant Orgo can run standalone and can be hosted by Koali Spaces as a `local_module_surface` inside the existing Koali `GlobalShell`. Koali hosting/capability projections never replace Orgo business authorization. Orgo revalidates identity, organization/tenant, RBAC and policy for protected mutations. See `../UI_AND_KOALI_INTEGRATION.md`. ## 20. Patterns explicitly not selected now Do not introduce these as default Orgo architecture without a measured requirement and a new decision record: - Task/Case/Workflow microservices; - Event Sourcing; - mandatory Kafka/RabbitMQ/Redis broker; - separate BFF service; - sharding/cell architecture/service mesh. ================================================================================================ FILE: Docs/Technical-Reference/v3/2-orgo-documentation-index.md AUTHORITY: reference CONTENT_ROLE: knowledge CONTENT_SHA256: 4f9b300feae5109e99738b92e7eea956ab7f3af220f77ad0c3a7cce1c5b8d79b CONTENT_BYTES: 31141 ================================================================================================ > **Legacy/reference document.** This file is retained for historical detail and may describe earlier implementation assumptions. For current architecture, use `../TARGET_ARCHITECTURE.md` plus the concise canonical v3 files whose names begin with `1-Orgo`, `2-Orgo`, etc. When this document conflicts with those sources or the physical code/schema authority, it is non-canonical.  Index Role of this document in the Orgo set Orgo mental model (orientation) 1.1 Multi‑tenant backbone 1.2 Signals → Cases & Tasks 1.3 Label system (how routing works) 1.4 Domain modules 1.5 Profiles, Insights & guardrails 1.6 What Orgo is (and is not) Global invariants & enums (locked) 2.1 Environments (ENVIRONMENT) 2.2 Multi‑tenancy & identity invariants 2.3 Task lifecycle (TASK_STATUS) 2.4 Case lifecycle (CASE_STATUS) 2.5 Priority & severity (TASK_PRIORITY, TASK_SEVERITY) 2.6 Visibility & privacy (VISIBILITY, COMMENT_VISIBILITY) 2.7 Log categories & levels (LOG_CATEGORY, LOG_LEVEL) 2.8 Notification channels & scope (NOTIFICATION_CHANNEL, NOTIFICATION_SCOPE) 2.9 Canonical label string format 2.10 Canonical Task field set (JSON contract) 2.11 Canonical Case field skeleton Configuration system (YAML‑based, environment‑aware) 3.1 Directory layout 3.2 Common metadata & validation 3.3 Database config 3.4 Email config 3.5 Logging config Core Services – contracts & checklists 4.1 Workflow Engine 4.2 Email Gateway 4.3 Task Handler 4.4 Notification Service 4.5 Persistence & offline sync 4.6 Logging & security hooks Domain Modules – position & invariants 5.1 Directory & naming 5.2 Domain config rules 5.3 Handler hooks (behaviour) Organization profiles & behavioural tuning 6.1 Profile schema (summary) 6.2 Example profile mapping Insights & cyclic overview integration Guardrails – visibility, audit, compliance Testing & operational checklists Summary – what this document locks # Orgo v3 – Doc 2/8 **Foundations, Locked Variables & Operational Checklists** --- ## 0. Role of this document in the Orgo set This document is the **foundation layer** for Orgo v3. It defines: * The **global invariants** Orgo relies on (multi‑tenancy, identity model). * The **locked enums and canonical field sets** for Tasks, Cases, labels, logging, and notifications. * How **configuration** is structured/validated across environments. * The **contracts + checklists** that Core Services and Domain Modules must respect. * How **profiles, insights, and guardrails** plug into the platform. It is implementation‑agnostic (TS/NestJS, Python, etc.) and sits under Docs: * **Doc 1 – Database Schema Reference (Custom Tables)** – physical schema and enums. * **Doc 3 – Domain Modules (Orgo v3)** – domain adapters over the core Task/Case engine. * **Doc 4 – Functional Code‑Name Inventory** – mapping from features to services/jobs/hooks. * **Doc 5 – Core Services Specification** – detailed headless services (email, tasks, workflows, logging). * **Doc 6 – Insights Module Config Parameters** and the **profiles YAML** – analytics & behavioural profiles. * **Doc 8 – Cyclic Overview & Universal Flow Rules** – label semantics, JSON contracts, cyclic reviews. If anything here conflicts with **Doc 1** (schema) or the actual DB migrations, **Doc 1 wins** and this doc must be updated. The intended conflict-resolution order across the Orgo v3 spec is: 1. **Doc 1 – Database Schema Reference** (physical tables & enums). 2. **Doc 2 – Foundations (this document)** (canonical enums, Task/Case JSON field sets, global invariants). 3. **Doc 8 – Cyclic Overview & Universal Flow Rules** (label semantics, lifecycles, flow). 4. Domain-specific and implementation docs (Docs 3–7, code inventories). Lower-numbered docs must not be overridden by higher-numbered ones. --- ## 1. Orgo mental model (non‑normative orientation) This section explains how the rest of the spec hangs together. It is descriptive, not a place to introduce new enums. ### 1.1 Multi‑tenant backbone * Orgo is **multi‑tenant** – one deployment serves many organizations. * Every org is a row in `organizations`, identified by `organization_id` with timezone, locale, status, and a linked **organization profile**. * Every record that “belongs to” an org (email, task, case, profile, notification, log, etc.) carries `organization_id` for isolation. * Two key identity concepts: * **User accounts** (`user_accounts`) – who logs into Orgo. * **Person profiles** (`person_profiles`) – who things are *about* (students, players, employees, community members), regardless of login. Permissions are expressed in terms of **roles** and **permissions** attached to user accounts, with optional scoping by team/location. ### 1.2 Signals → Cases & Tasks Orgo’s core job is to **ingest messy signals and turn them into structured work**: * **Signals** come from: * Email (`email_messages` + `email_threads`), including attachments and classifier metadata. * HTTP APIs / UIs (`TaskController.createTask`, domain endpoints). * Offline imports & sync (`offline_nodes`, `sync_sessions`, `email_archive_import_batches`). * Signals pass through the **Email Gateway** and **Workflow Engine**, which decide: * Whether to **open a Case** (`cases`), * Whether to **create a Task** (`tasks`), * Which **domain** (`type`), **category** (`request/incident/...`), and **role** should own it. The **Task** is the **canonical unit of work**, defined once in Doc 1 and reused everywhere; **Cases** are long‑lived containers that group Tasks, context and patterns. ### 1.3 Label system (how routing works) Every Case and Task carries a **structured label**: ```text .. ``` Example: `100.94.Operations.Safety`: * `100` = broadcast to department heads (vertical level). * `.9` = Crisis & emergency information. * `.4` = Report. * `Operations.Safety` = horizontal role (functional area). This label informs: * **Routing** – which queues/roles the work goes to. * **Visibility default** – how sensitive it is. * **Analytics & patterns** – what “kind” of incident it is. Special bases `10`, `100`, `1000` are **broadcasts**. They are **informational by default** – they do not automatically spawn mandatory Tasks unless a workflow rule says so. ### 1.4 Domain modules Domain modules (Maintenance, HR, Education, etc.): * Do **not** own their own task tables or lifecycles. * Are thin adapters over the global `Task`/`Case` model: * A config file `_module.yaml` (allowed categories, subtypes, email patterns, routing hints). * A handler `_handler.py` with hooks such as `on_task_create`, `on_task_update`. They plug into the **central Task handler + Workflow Engine**; all domain behaviour is expressed via config, metadata and hooks, not separate schemas. ### 1.5 Profiles, Insights & guardrails * **Profiles** (friend group, hospital, advocacy group, retail chain, military org, environmental group, artist collective, etc.) define **reactivity, transparency, review cadence, retention, pattern sensitivity, logging depth and automation** for an organization. * **Insights** (star schema, ETL/Airflow, pattern detection) continuously scan Tasks/Cases, wellbeing check‑ins, groups, etc., and feed patterns back as work items and audit Cases. * **Guardrails** – visibility enums, logging/audit tables, security events and export rules – ensure Orgo is safe for high‑sensitivity domains (e.g. HR, hospitals) while still usable for low‑stakes groups. ### 1.6 What Orgo is (and is not) Orgo is: * A **unified, schema‑driven case & task platform** that multiple orgs and domains plug into. * A **routing + escalation + pattern‑detection engine** over signals and work. Orgo is **not**: * A generic CRM / ERP / accounting system. * A stand‑alone kanban board toy. --- ## 2. Global invariants & enums (locked) These enums and core concepts are **canonical** for Orgo v3. Other docs and code must reference them rather than introduce alternatives. ### 2.1 Environments ```text ENVIRONMENT = { "dev", "staging", "prod", "offline" } ``` * `dev` – local / developer environments. * `staging` – pre‑production staging. * `prod` – production. * `offline` – disconnected nodes that sync later. Every config file must include: ```yaml metadata: environment: "" version: "3.x" last_updated: "YYYY-MM-DD" ``` ### 2.2 Multi‑tenancy & identity invariants * Every org has `organizations.id` → `organization_id` elsewhere. * Every org may have **one active profile** (`organization_profiles`). * Every Task/Case/Email/Notification/Log: * Either belongs to exactly one org (`organization_id` NOT NULL), * Or is a global default/config row (`organization_id` NULL). User vs Person: * **User** (`user_accounts`) = login account in an org. * **Person** (`person_profiles`) = a human subject (student, employee, player, community member), optionally linked to a user. ### 2.3 Task lifecycle Canonical DB enum: `task_status_enum`. ```text TASK_STATUS = { "PENDING", "IN_PROGRESS", "ON_HOLD", "COMPLETED", "FAILED", "ESCALATED", "CANCELLED" } ``` Semantics: * `PENDING` – created, not started. * `IN_PROGRESS` – someone is actively working on it. * `ON_HOLD` – paused (waiting on dependency/decision). * `COMPLETED` – done successfully. * `FAILED` – attempted but unsuccessful; further action needed. * `ESCALATED` – escalated to higher authority/queue. * `CANCELLED` – explicitly stopped. **Rules:** * These are the **only** allowed values in DB, APIs, logs for Task status. * State machine constraints and allowed transitions are specified in **Doc 5** and must be enforced everywhere. ### 2.4 Case lifecycle Canonical DB enum: `cases.status`. ```text CASE_STATUS = { "open", "in_progress", "resolved", "archived" } ``` * `open` – new Case, not yet being actively worked. * `in_progress` – actively being handled (has active Tasks). * `resolved` – outcome reached and communicated. * `archived` – closed; kept for history/compliance. These are the only allowed values for `cases.status`. ### 2.5 Priority & severity ```text TASK_PRIORITY = { "LOW", "MEDIUM", "HIGH", "CRITICAL" } TASK_SEVERITY = { "MINOR", "MODERATE", "MAJOR", "CRITICAL" } ``` * **Priority** – how fast we want to act (SLA / scheduling). * **Severity** – how bad it is if we don’t (impact / risk). All Task and Case severity fields MUST use `TASK_SEVERITY` (DB: `task_severity_enum`). ### 2.6 Visibility & privacy Canonical DB enum: `visibility_enum`. ```text VISIBILITY = { "PUBLIC", # visible across the org (subject to RBAC) "INTERNAL", # limited to org‑internal teams/roles "RESTRICTED", # minimal set of users/roles "ANONYMISED" # pseudonymised or fully anonymised content } ``` Examples: * Public safety broadcast → `PUBLIC`. * HR or clinical report → often `RESTRICTED` or `ANONYMISED` depending on profile and policies. Visibility interacts with exports and analytics per Doc 6 (e.g. only `PUBLIC`/`INTERNAL` rows can be raw-exported by default). #### 2.6.1 Comment-level visibility (Task comments) Task comments have their own per-comment visibility enum, stored in `task_comments.visibility`: ```text COMMENT_VISIBILITY = { "internal_only", # visible only to internal staff on the case/task "requester_visible", # visible to the original requester plus internal staff "org_wide" # visible to all authorized users in the organization } ``` This is a **comment-level audience flag**, distinct from the global `VISIBILITY` enum used on Tasks and Cases. Implementations must not introduce additional values beyond these three without updating the schema and this document. ### 2.7 Log categories & levels ```text LOG_CATEGORY = { "WORKFLOW", "TASK", "SYSTEM", "SECURITY", "EMAIL" } LOG_LEVEL = { "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL" } ``` `WARNING` is the canonical log‑level value. Configuration loaders may accept `WARN` as a synonym and normalise it to `WARNING`, but `WARN` is not itself a first‑class enum value. Implementations must treat `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL` as the complete `LOG_LEVEL` set. Minimum fields per log entry: ```jsonc { "timestamp": "2025-11-18T10:01:02Z", "level": "INFO", "category": "WORKFLOW", "message": "Task routed to maintenance queue", "identifier": "task_id:12345" } ``` Logging and audit tables (`activity_logs`, `security_events`, `system_metric_snapshots`) store structured data aligned with these enums. ### 2.8 Notification channels & scope ```text NOTIFICATION_CHANNEL = { "EMAIL", "SMS", "IN_APP", "WEBHOOK" } ``` * `EMAIL` is mandatory; others are optional per deployment. * DB `notifications.channel` stores lower‑case versions (`email`, `in_app`, `sms`, `webhook`). * `PUSH` is not a distinct channel in Orgo v3; mobile push, if implemented, is modelled via `IN_APP` plus client‑side delivery. Notification scope (metadata / workflow rules): ```text NOTIFICATION_SCOPE = { "user", # single user "team", # owning team "department", # functional group / department "org_wide" # whole org } ``` JSON/YAML store these as shown; UIs may map to friendlier labels. ### 2.9 Canonical label string format Canonical label format (for `tasks.label`, `cases.label`): ```text