diff --git a/README.md b/README.md index 9619f68..2bf39c9 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ identifier belongs in it. | Content memory adapter | `cib-contenu-memory` | [content-memory](content-memory/module.yaml) | | Support memory adapter | `cib-accompagnement-memory` | [support-memory](support-memory/module.yaml) | | Image studio | `image-studio` | [image-studio](image-studio/module.yaml) | +| Company profile | `cib-profile` | [profile](profile/module.yaml) | [modules.json](modules.json) is generated from the manifests. The enriched [catalog.json](catalog.json) is the public index of the Modules: for each one a diff --git a/catalog.json b/catalog.json index f1825fb..df3cc78 100644 --- a/catalog.json +++ b/catalog.json @@ -370,6 +370,49 @@ "workflows": 9, "miniapps": 6 }, + { + "key": "cib-profile", + "name": "Company-in-a-Box — company profile", + "version": "0.1.0", + "subpath": "profile", + "manifest": "profile/module.yaml", + "manifest_sha256": "92c00919b3051a5229e3bba7bc9d0979c85cb91a4ff5fb9a0cd0b576b7add09e", + "tree_sha256": "7bbbea820e4971d3005a2bf3eaefa81cf380f7b6fb3b8f0aa3188e975f5522f5", + "description": { + "en": "Company profile: identity, address, optional bank details, colours, fonts and logo reference, saved once and projected as the company and brand context of document templates.", + "fr": "Fiche entreprise : identité, adresse, coordonnées bancaires facultatives, couleurs, polices et référence du logo, enregistrées une fois et projetées en contexte company et brand des gabarits de documents." + }, + "capabilities": [ + "profile", + "company", + "brand", + "documents" + ], + "actions": [ + { + "key": "save", + "name": "save" + } + ], + "queries": [ + "read" + ], + "requires": { + "runtimes": [ + "deno" + ], + "language_model": false, + "connectors": [], + "credentials": [], + "modules": [] + }, + "price": { + "model": "free" + }, + "maturity": "preview", + "workflows": 2, + "miniapps": 1 + }, { "key": "cib-veille", "name": "Company-in-a-Box — Veille", diff --git a/catalog/profile.yaml b/catalog/profile.yaml new file mode 100644 index 0000000..8e6f39f --- /dev/null +++ b/catalog/profile.yaml @@ -0,0 +1,17 @@ +{ + "capabilities": [ + "profile", + "company", + "brand", + "documents" + ], + "credentials": [], + "description": { + "en": "Company profile: identity, address, optional bank details, colours, fonts and logo reference, saved once and projected as the company and brand context of document templates.", + "fr": "Fiche entreprise : identité, adresse, coordonnées bancaires facultatives, couleurs, polices et référence du logo, enregistrées une fois et projetées en contexte company et brand des gabarits de documents." + }, + "price": { + "model": "free" + }, + "schema": "agentmaurice.module_catalog_entry/v1" +} diff --git a/inventory/modules.json b/inventory/modules.json index 441c72f..960dfa2 100644 --- a/inventory/modules.json +++ b/inventory/modules.json @@ -2039,6 +2039,93 @@ "publication": "present in historical GitHub source at specified commit", "migration_m5_m6": "to define and qualify; deployment status is not inferred" }, + { + "key": "cib-profile", + "version": "0.1.0", + "manifest": "profile/module.yaml", + "workflows": 2, + "miniapps": 1, + "source": { + "repository": "github.com/agentmaurice/modules", + "native": true + }, + "generators_and_composers": [ + "tooling/profile/build.py", + "tooling/profile/compose.py" + ], + "resources": { + "workflows": [ + "profile/agents/main/workflows/cib-admin-profile-save.json", + "profile/agents/main/workflows/cib-profile-read.json" + ], + "miniapps": [ + "profile/agents/main/miniapps/cib-profile-console.json" + ], + "sha256": { + "profile/module.yaml": "92c00919b3051a5229e3bba7bc9d0979c85cb91a4ff5fb9a0cd0b576b7add09e", + "profile/agents/main/workflows/cib-admin-profile-save.json": "9a9e0e216160591f76827638cc5b8fd0fb530514b84c590ed7193bbc1d81e05b", + "profile/agents/main/workflows/cib-profile-read.json": "02fa00329517e2562a2b6fce355fd68c7fdc3d05d7ccb5e9341e954cff4b94ab", + "profile/agents/main/miniapps/cib-profile-console.json": "3182daee089e86898b9b4989ab9f8e363d01abdea7e60756d185300f4aaf0659" + } + }, + "workflow_actions": { + "profile/agents/main/workflows/cib-admin-profile-save.json": { + "workflow_id": "cib-admin-profile-save", + "actions": [ + { + "path": "/actions/0", + "id": "save", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "5853fe3e005b5ce2b39f93cf9cde9cbcda2c126d6146e7b0d90e4b971aceb98f" + } + ] + }, + "profile/agents/main/workflows/cib-profile-read.json": { + "workflow_id": "cib-profile-read", + "actions": [ + { + "path": "/actions/0", + "id": "read", + "type": "code_execution", + "runtime": "deno", + "runtime_source": "contract default", + "code_sha256": "94421698ed14a05dd012ecf5e7f44906576fe91f9cf93c75a86caeddc8c7bcc0" + } + ] + } + }, + "provides": { + "actions": [ + { + "key": "save", + "workflow_id": "cib-admin-profile-save", + "workflow_version": "1" + } + ], + "queries": [ + { + "key": "read", + "workflow_id": "cib-profile-read", + "workflow_version": "1" + } + ], + "apps": [ + { + "key": "profile-console", + "miniapp_id": "cib-profile-console", + "miniapp_version": "1" + } + ] + }, + "requires": {}, + "composition_dependencies": [], + "known_consumers": [], + "language": "English source", + "runtime": "Static observation of Agent Spec V2 definitions; runtime execution and qualification are not inferred", + "publication": "native to this repository, unpublished" + }, { "key": "cib-accompagnement", "version": "0.2.4", diff --git a/modules.json b/modules.json index ae8eec1..760a62c 100644 --- a/modules.json +++ b/modules.json @@ -50,6 +50,13 @@ "workflows": 9, "miniapps": 6 }, + { + "key": "cib-profile", + "version": "0.1.0", + "manifest": "profile/module.yaml", + "workflows": 2, + "miniapps": 1 + }, { "key": "cib-accompagnement", "version": "0.2.4", diff --git a/profile/agents/main/miniapps/cib-profile-console.json b/profile/agents/main/miniapps/cib-profile-console.json new file mode 100644 index 0000000..5239b85 --- /dev/null +++ b/profile/agents/main/miniapps/cib-profile-console.json @@ -0,0 +1,350 @@ +{ + "$schema": "agentmaurice.miniapp/v2", + "schema_version": 2, + "kind": "miniapp", + "miniapp_id": "cib-profile-console", + "version": "1", + "title": "Company profile", + "description": "Edit the company profile (identity, address, optional bank details, colours, fonts, logo reference and page margins) used by generated documents. One record, saved by a cib_admin with a manual confirmation.", + "ui": { + "renderer": "component", + "component": "company-in-a-box", + "configuration": { + "layout": [ + { + "type": "callout", + "title": "Company profile", + "tone": "info", + "value": "One shared profile for your documents. Load it, check the colour preview, then open the form \"Company profile - save\" in the available interactions. The logo is a storage:// reference to a file already in Storage; uploading a logo is not available here." + }, + { + "type": "button", + "label": "Load the company profile", + "on_click": "read" + }, + { + "type": "section", + "title": "Current record", + "children": [ + { + "type": "stat", + "label": "Revision", + "value": { + "state": "profile.revision" + } + }, + { + "type": "stat", + "label": "Legal name", + "value": { + "state": "profile.fields.legal_name" + } + }, + { + "type": "stat", + "label": "Logo reference", + "value": { + "state": "profile.fields.logo_ref" + } + }, + { + "type": "text", + "value": { + "state": "profile.message" + } + } + ] + }, + { + "type": "section", + "title": "Colour preview", + "children": [ + { + "type": "table", + "columns": [ + "token", + "hex", + "contrast_on_background" + ], + "column_labels": { + "token": "Token", + "hex": "Colour", + "contrast_on_background": "Contrast on background" + }, + "rows": { + "state": "profile.color_preview" + } + } + ] + }, + { + "type": "section", + "title": "Last save", + "children": [ + { + "type": "text", + "value": { + "state": "result.message" + } + }, + { + "type": "table", + "columns": [ + "token", + "hex", + "contrast_on_background" + ], + "column_labels": { + "token": "Token", + "hex": "Colour", + "contrast_on_background": "Contrast on background" + }, + "rows": { + "state": "result.color_preview" + } + } + ] + } + ] + } + }, + "state_schema": { + "type": "object", + "properties": { + "legal_name": { + "type": "string" + }, + "trade_name": { + "type": "string" + }, + "legal_form": { + "type": "string" + }, + "share_capital": { + "type": "string" + }, + "siren": { + "type": "string" + }, + "siret": { + "type": "string" + }, + "vat_number": { + "type": "string" + }, + "rcs": { + "type": "string" + }, + "address_line1": { + "type": "string" + }, + "address_line2": { + "type": "string" + }, + "address_postal_code": { + "type": "string" + }, + "address_city": { + "type": "string" + }, + "address_country": { + "type": "string" + }, + "email": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "website": { + "type": "string" + }, + "legal_mentions": { + "type": "string" + }, + "bank_account_holder": { + "type": "string" + }, + "bank_iban": { + "type": "string" + }, + "bank_bic": { + "type": "string" + }, + "bank_name": { + "type": "string" + }, + "color_primary": { + "type": "string" + }, + "color_secondary": { + "type": "string" + }, + "color_accent": { + "type": "string" + }, + "color_text": { + "type": "string" + }, + "color_muted": { + "type": "string" + }, + "color_background": { + "type": "string" + }, + "font_heading": { + "type": "string" + }, + "font_body": { + "type": "string" + }, + "font_mono": { + "type": "string" + }, + "logo_ref": { + "type": "string" + }, + "logo_alt": { + "type": "string" + }, + "margin_top": { + "type": "string" + }, + "margin_right": { + "type": "string" + }, + "margin_bottom": { + "type": "string" + }, + "margin_left": { + "type": "string" + }, + "page_size": { + "type": "string" + }, + "expected_revision": { + "type": "string" + }, + "confirmation_manuelle": { + "type": "string" + }, + "profile": { + "type": "object" + }, + "result": { + "type": "object" + } + } + }, + "initial_state": { + "legal_name": "", + "trade_name": "", + "legal_form": "", + "share_capital": "", + "siren": "", + "siret": "", + "vat_number": "", + "rcs": "", + "address_line1": "", + "address_line2": "", + "address_postal_code": "", + "address_city": "", + "address_country": "", + "email": "", + "phone": "", + "website": "", + "legal_mentions": "", + "bank_account_holder": "", + "bank_iban": "", + "bank_bic": "", + "bank_name": "", + "color_primary": "", + "color_secondary": "", + "color_accent": "", + "color_text": "", + "color_muted": "", + "color_background": "", + "font_heading": "", + "font_body": "", + "font_mono": "", + "logo_ref": "", + "logo_alt": "", + "margin_top": "", + "margin_right": "", + "margin_bottom": "", + "margin_left": "", + "page_size": "A4", + "expected_revision": "0", + "confirmation_manuelle": "false", + "profile": { + "found": false, + "revision": 0, + "color_preview": [], + "fields": {}, + "message": "No profile loaded." + }, + "result": { + "message": "No action." + } + }, + "events": [ + { + "event_id": "read", + "trigger": "action.click", + "workflow": { + "workflow_id": "cib-profile-read", + "input": {} + }, + "result_to_state": "profile" + }, + { + "event_id": "save", + "trigger": "form.submit", + "workflow": { + "workflow_id": "cib-admin-profile-save", + "input": { + "legal_name": "{{ state.legal_name }}", + "trade_name": "{{ state.trade_name }}", + "legal_form": "{{ state.legal_form }}", + "share_capital": "{{ state.share_capital }}", + "siren": "{{ state.siren }}", + "siret": "{{ state.siret }}", + "vat_number": "{{ state.vat_number }}", + "rcs": "{{ state.rcs }}", + "address_line1": "{{ state.address_line1 }}", + "address_line2": "{{ state.address_line2 }}", + "address_postal_code": "{{ state.address_postal_code }}", + "address_city": "{{ state.address_city }}", + "address_country": "{{ state.address_country }}", + "email": "{{ state.email }}", + "phone": "{{ state.phone }}", + "website": "{{ state.website }}", + "legal_mentions": "{{ state.legal_mentions }}", + "bank_account_holder": "{{ state.bank_account_holder }}", + "bank_iban": "{{ state.bank_iban }}", + "bank_bic": "{{ state.bank_bic }}", + "bank_name": "{{ state.bank_name }}", + "color_primary": "{{ state.color_primary }}", + "color_secondary": "{{ state.color_secondary }}", + "color_accent": "{{ state.color_accent }}", + "color_text": "{{ state.color_text }}", + "color_muted": "{{ state.color_muted }}", + "color_background": "{{ state.color_background }}", + "font_heading": "{{ state.font_heading }}", + "font_body": "{{ state.font_body }}", + "font_mono": "{{ state.font_mono }}", + "logo_ref": "{{ state.logo_ref }}", + "logo_alt": "{{ state.logo_alt }}", + "margin_top": "{{ state.margin_top }}", + "margin_right": "{{ state.margin_right }}", + "margin_bottom": "{{ state.margin_bottom }}", + "margin_left": "{{ state.margin_left }}", + "page_size": "{{ state.page_size }}", + "expected_revision": "{{ state.expected_revision }}", + "confirmation_manuelle": "{{ state.confirmation_manuelle }}" + } + }, + "result_to_state": "result" + } + ] +} diff --git a/profile/agents/main/workflows/cib-admin-profile-save.json b/profile/agents/main/workflows/cib-admin-profile-save.json new file mode 100644 index 0000000..77373f7 --- /dev/null +++ b/profile/agents/main/workflows/cib-admin-profile-save.json @@ -0,0 +1,338 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "kind": "workflow", + "workflow_id": "cib-admin-profile-save", + "version": "1", + "title": "Company profile — save", + "description": "Saves the company profile with an expected revision. Restricted to the cib_admin role (the cib-admin- prefix is what tooling/enterprise-admin/service_roles.py maps to it) and to a manual confirmation. The logo is a storage:// reference; there is no upload. Bank details are optional and checked by shape only.", + "forms": [ + { + "id": "save", + "title": "Company profile — save", + "fields": [ + { + "name": "legal_name", + "title": "Legal name", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.legal_name }}" + }, + { + "name": "trade_name", + "title": "Trade name", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.trade_name }}" + }, + { + "name": "legal_form", + "title": "Legal form", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.legal_form }}" + }, + { + "name": "share_capital", + "title": "Share capital", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.share_capital }}" + }, + { + "name": "siren", + "title": "SIREN", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.siren }}" + }, + { + "name": "siret", + "title": "SIRET", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.siret }}" + }, + { + "name": "vat_number", + "title": "VAT number", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.vat_number }}" + }, + { + "name": "rcs", + "title": "Trade register (RCS)", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.rcs }}" + }, + { + "name": "address_line1", + "title": "Address, line 1", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.address_line1 }}" + }, + { + "name": "address_line2", + "title": "Address, line 2", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.address_line2 }}" + }, + { + "name": "address_postal_code", + "title": "Postal code", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.address_postal_code }}" + }, + { + "name": "address_city", + "title": "City", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.address_city }}" + }, + { + "name": "address_country", + "title": "Country", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.address_country }}" + }, + { + "name": "email", + "title": "E-mail", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.email }}" + }, + { + "name": "phone", + "title": "Phone", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.phone }}" + }, + { + "name": "website", + "title": "Website", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.website }}" + }, + { + "name": "legal_mentions", + "title": "Legal mentions", + "type": "text", + "required": false, + "default": "{{ state.profile.fields.legal_mentions }}" + }, + { + "name": "bank_account_holder", + "title": "Bank account holder", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.bank_account_holder }}" + }, + { + "name": "bank_iban", + "title": "IBAN", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.bank_iban }}" + }, + { + "name": "bank_bic", + "title": "BIC", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.bank_bic }}" + }, + { + "name": "bank_name", + "title": "Bank name", + "type": "string", + "required": false, + "default": "{{ state.profile.fields.bank_name }}" + }, + { + "name": "color_primary", + "title": "Primary colour (#RRGGBB)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.color_primary }}" + }, + { + "name": "color_secondary", + "title": "Secondary colour (#RRGGBB)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.color_secondary }}" + }, + { + "name": "color_accent", + "title": "Accent colour (#RRGGBB)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.color_accent }}" + }, + { + "name": "color_text", + "title": "Text colour (#RRGGBB)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.color_text }}" + }, + { + "name": "color_muted", + "title": "Muted colour (#RRGGBB)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.color_muted }}" + }, + { + "name": "color_background", + "title": "Background colour (#RRGGBB)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.color_background }}" + }, + { + "name": "font_heading", + "title": "Heading font family", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.font_heading }}" + }, + { + "name": "font_body", + "title": "Body font family", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.font_body }}" + }, + { + "name": "font_mono", + "title": "Monospace font family", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.font_mono }}" + }, + { + "name": "logo_ref", + "title": "Logo reference (storage://...)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.logo_ref }}" + }, + { + "name": "logo_alt", + "title": "Logo alternative text", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.logo_alt }}" + }, + { + "name": "page_size", + "title": "Page size", + "type": "select", + "required": true, + "options": [ + { + "value": "A4", + "label": "A4" + }, + { + "value": "Letter", + "label": "Letter" + } + ], + "default": "A4" + }, + { + "name": "margin_top", + "title": "Top margin (mm)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.margin_top }}" + }, + { + "name": "margin_right", + "title": "Right margin (mm)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.margin_right }}" + }, + { + "name": "margin_bottom", + "title": "Bottom margin (mm)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.margin_bottom }}" + }, + { + "name": "margin_left", + "title": "Left margin (mm)", + "type": "string", + "required": true, + "default": "{{ state.profile.fields.margin_left }}" + }, + { + "name": "expected_revision", + "title": "Expected revision (0 to create)", + "type": "string", + "required": true, + "default": "{{ state.profile.revision }}" + }, + { + "name": "confirmation_manuelle", + "title": "Manual confirmation", + "type": "select", + "required": true, + "options": [ + { + "value": "false", + "label": "No" + }, + { + "value": "true", + "label": "Yes" + } + ], + "default": "false" + } + ], + "actions_on_submit": [ + "save" + ] + } + ], + "actions": [ + { + "id": "save", + "type": "code_execution", + "context": { + "allowed_tools": [ + "recipe--application_data_v1" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\nconst input = {{ json . }};\n\nconst NAMESPACE = \"cib-profile\";\nconst RECORD_KEY = \"company-profile\";\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nconst BANK_TEXT = {account_holder: 200, bank_name: 200};\nconst COMPANY_KEYS = [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"];\nconst BRAND_KEYS = [\"colors\", \"fonts\", \"logo\", \"page\"];\n\nfunction fail(code) { throw new Error(code); }\nfunction isObject(value) { return value !== null && typeof value === \"object\" && !Array.isArray(value); }\nfunction onlyKeys(value, allowed, name) { for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(name + \"_unknown_field\"); }\nfunction text(value, name, max, required) {\n if (value === undefined || value === null || value === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof value !== \"string\" || value.length > max) fail(name + \"_invalid\");\n const trimmed = value.trim();\n if (required && !trimmed) fail(name + \"_required\");\n return trimmed;\n}\nfunction margin(value, name) {\n const raw = typeof value === \"number\" ? String(value) : value;\n if (typeof raw !== \"string\" || !/^[0-9]{1,3}(\\.[0-9]{1,2})?$/.test(raw.trim())) fail(name + \"_invalid\");\n const number = Number(raw.trim());\n if (number > 100) fail(name + \"_invalid\");\n return number;\n}\nfunction logoRef(value) {\n if (typeof value !== \"string\" || !/^storage:\\/\\/[^\\s]{1,500}$/.test(value) || value.includes(\"..\") || value.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n return value;\n}\n\n// Canonical body, the stored shape: { schema_version, company, brand }. company.logo is never stored: it is derived from brand.logo.ref on read.\nfunction normalizeBody(body) {\n if (!isObject(body) || body.schema_version !== 1) fail(\"body_schema_invalid\");\n onlyKeys(body, [\"schema_version\", \"company\", \"brand\"], \"body\");\n const c = body.company, b = body.brand;\n if (!isObject(c) || !isObject(b)) fail(\"body_schema_invalid\");\n if (c.logo !== undefined) fail(\"company_logo_derived_from_brand\");\n onlyKeys(c, COMPANY_KEYS, \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const value = text(c[key], key, max, false); if (value) company[key] = value; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const value = text(c.address[part], \"address_\" + part, 200, false); if (value) address[part] = value; }\n if (Object.keys(address).length) {\n for (const part of [\"line1\", \"postal_code\", \"city\", \"country\"]) if (!address[part]) fail(\"address_\" + part + \"_required\");\n company.address = address;\n }\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const [key, max] of Object.entries(BANK_TEXT)) { const value = text(c.bank[key], \"bank_\" + key, max, false); if (value) bank[key] = value; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n if (typeof c.bank.iban !== \"string\") fail(\"iban_invalid\");\n const iban = c.bank.iban.replace(/\\s+/g, \"\").toUpperCase();\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n if (typeof c.bank.bic !== \"string\") fail(\"bic_invalid\");\n const bic = c.bank.bic.replace(/\\s+/g, \"\").toUpperCase();\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, BRAND_KEYS, \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n onlyKeys(b.colors, COLOR_TOKENS, \"colors\");\n onlyKeys(b.fonts, FONT_ROLES, \"fonts\");\n onlyKeys(b.logo, [\"ref\", \"alt\"], \"logo\");\n onlyKeys(b.page, [\"size\", \"margins_mm\"], \"page\");\n onlyKeys(b.page.margins_mm, MARGIN_SIDES, \"margins_mm\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); onlyKeys(b.fonts[role], [\"family\"], \"font_\" + role); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) margins_mm[side] = margin(b.page.margins_mm[side], \"margin_\" + side);\n const brand = {colors, fonts, logo: {ref: logoRef(b.logo.ref), alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n return {schema_version: 1, company, brand};\n}\n\n// Flat form input -> structured body.\nfunction bodyFromFields(input) {\n if (!isObject(input)) fail(\"input_invalid\");\n const field = (name) => (input[name] === undefined || input[name] === null ? \"\" : input[name]);\n const company = {legal_name: field(\"legal_name\")};\n for (const key of Object.keys(COMPANY_TEXT)) if (field(key) !== \"\") company[key] = field(key);\n const address = {};\n for (const part of ADDRESS_PARTS) if (field(\"address_\" + part) !== \"\") address[part] = field(\"address_\" + part);\n if (Object.keys(address).length) company.address = address;\n const bank = {};\n if (field(\"bank_account_holder\") !== \"\") bank.account_holder = field(\"bank_account_holder\");\n if (field(\"bank_iban\") !== \"\") bank.iban = field(\"bank_iban\");\n if (field(\"bank_bic\") !== \"\") bank.bic = field(\"bank_bic\");\n if (field(\"bank_name\") !== \"\") bank.bank_name = field(\"bank_name\");\n if (Object.keys(bank).length) company.bank = bank;\n const colors = {};\n for (const token of COLOR_TOKENS) colors[token] = field(\"color_\" + token);\n const fonts = {};\n for (const role of FONT_ROLES) fonts[role] = {family: field(\"font_\" + role)};\n const margins_mm = {};\n for (const side of MARGIN_SIDES) margins_mm[side] = field(\"margin_\" + side);\n return {schema_version: 1, company, brand: {colors, fonts, logo: {ref: field(\"logo_ref\"), alt: field(\"logo_alt\")}, page: {size: field(\"page_size\"), margins_mm}}};\n}\n\n// Stored body -> flat strings, to prefill the form.\nfunction toFields(body) {\n const c = body.company, b = body.brand, a = c.address || {}, k = c.bank || {};\n const fields = {legal_name: c.legal_name, address_line1: a.line1 || \"\", address_line2: a.line2 || \"\", address_postal_code: a.postal_code || \"\", address_city: a.city || \"\", address_country: a.country || \"\", bank_account_holder: k.account_holder || \"\", bank_iban: k.iban || \"\", bank_bic: k.bic || \"\", bank_name: k.bank_name || \"\"};\n for (const key of Object.keys(COMPANY_TEXT)) fields[key] = c[key] || \"\";\n for (const token of COLOR_TOKENS) fields[\"color_\" + token] = b.colors[token];\n for (const role of FONT_ROLES) fields[\"font_\" + role] = b.fonts[role].family;\n fields.logo_ref = b.logo.ref; fields.logo_alt = b.logo.alt; fields.page_size = b.page.size;\n for (const side of MARGIN_SIDES) fields[\"margin_\" + side] = String(b.page.margins_mm[side]);\n return fields;\n}\n\n// The template/v1 context pair. The body maps onto company and brand as is; only company.logo is derived, from the single brand.logo source.\nfunction project(body) {\n const company = {...body.company};\n if (isObject(body.brand) && isObject(body.brand.logo) && typeof body.brand.logo.ref === \"string\" && body.brand.logo.ref !== \"\") company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction deepEqual(a, b) {\n if (a === b) return true;\n if (!a || !b || typeof a !== \"object\" || typeof b !== \"object\" || Array.isArray(a) !== Array.isArray(b)) return false;\n const ka = Object.keys(a), kb = Object.keys(b);\n return ka.length === kb.length && ka.every((key) => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key]));\n}\n\n// A stored body must already be canonical: it is projected as it is, never rewritten (no trimming, no dropped or added key).\nfunction checkedBody(raw) {\n if (!deepEqual(normalizeBody(raw), raw)) fail(\"stored_body_not_canonical\");\n return raw;\n}\n\n// Only the broker's explicit not-found code (NOT_FOUND, \"application data record not found\") means \"no profile yet\".\nfunction brokerCode(value) {\n if (isObject(value) && isObject(value.error)) return typeof value.error.code === \"string\" ? value.error.code : \"unknown\";\n return null;\n}\nfunction isNotFound(error) { return isObject(error) && error.code === \"NOT_FOUND\"; }\nfunction brokerFailure(code) { return \"broker_error_\" + String(code || \"unknown\").toLowerCase().replace(/[^a-z0-9_]/g, \"_\"); }\n\nfunction luminance(hex) {\n const channel = (offset) => { const v = parseInt(hex.slice(offset, offset + 2), 16) / 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };\n return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5);\n}\nfunction contrast(a, b) { const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); return Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100; }\nfunction colorPreview(brand) {\n return COLOR_TOKENS.map((token) => ({token, hex: brand.colors[token], contrast_on_background: contrast(brand.colors[token], brand.colors.background)}));\n}\n\nfunction brokerRecord(response) {\n const code = brokerCode(response);\n if (code !== null) fail(brokerFailure(code));\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!item || item.namespace !== NAMESPACE || item.key !== RECORD_KEY) fail(\"broker_record_identity_invalid\");\n if (!Number.isSafeInteger(item.revision) || item.revision < 0) fail(\"broker_revision_invalid\");\n const p = item.permissions;\n if (!p || typeof p.can_read !== \"boolean\" || typeof p.can_write !== \"boolean\" || typeof p.can_manage !== \"boolean\") fail(\"broker_permissions_invalid\");\n return item;\n}\n\nconst confirmed = input.confirmation_manuelle === true || input.confirmation_manuelle === \"true\";\nif (!confirmed) fail(\"manual_confirmation_required\");\nlet expected_revision = input.expected_revision;\nif (expected_revision === undefined || expected_revision === null || expected_revision === \"\") fail(\"expected_revision_required\");\nif (typeof expected_revision === \"string\" && /^[0-9]+$/.test(expected_revision)) expected_revision = Number(expected_revision);\nif (!Number.isSafeInteger(expected_revision) || expected_revision < 0) fail(\"expected_revision_invalid\");\nconst body = normalizeBody(bodyFromFields(input));\nconst response = await callTool(\"recipe--application_data_v1\", {operation: \"save\", namespace: NAMESPACE, record_key: RECORD_KEY, data: body, expected_revision});\nconst item = brokerRecord(response);\nconst stored = checkedBody(item.data);\nreturn {namespace: NAMESPACE, record_key: RECORD_KEY, revision: item.revision, owner_user_id: typeof item.owner_user_id === \"string\" ? item.owner_user_id : \"\", permissions: item.permissions, shares: Array.isArray(item.shares) ? item.shares.length : 0, profile: project(stored), color_preview: colorPreview(stored.brand), message: \"Company profile saved in the internal ACL store; no external effect. Other people read it only after an explicit per-person share.\", external_effect: false};", + "output_key": "result" + } + ], + "output": { + "namespace": "{{ result.namespace }}", + "record_key": "{{ result.record_key }}", + "revision": "{{ result.revision }}", + "owner_user_id": "{{ result.owner_user_id }}", + "permissions": "{{ result.permissions }}", + "shares": "{{ result.shares }}", + "profile": "{{ result.profile }}", + "color_preview": "{{ result.color_preview }}", + "message": "{{ result.message }}", + "external_effect": false + } +} diff --git a/profile/agents/main/workflows/cib-profile-read.json b/profile/agents/main/workflows/cib-profile-read.json new file mode 100644 index 0000000..98ae7e1 --- /dev/null +++ b/profile/agents/main/workflows/cib-profile-read.json @@ -0,0 +1,37 @@ +{ + "$schema": "agentmaurice.workflow/v2", + "schema_version": 2, + "kind": "workflow", + "workflow_id": "cib-profile-read", + "version": "1", + "title": "Company profile — read", + "description": "Reads the company profile record (namespace cib-profile, key company-profile) through the native broker and returns the body with the { company, brand } projection for template/v1. It needs read access on the record; it never reads another person's data.", + "actions": [ + { + "id": "read", + "type": "code_execution", + "context": { + "allowed_tools": [ + "recipe--application_data_v1" + ] + }, + "code": "import { callTool } from './tools/nats_bridge.ts';\n\nconst NAMESPACE = \"cib-profile\";\nconst RECORD_KEY = \"company-profile\";\nconst COLOR = /^#[0-9a-fA-F]{6}$/;\nconst IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/;\nconst BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/;\nconst COLOR_TOKENS = [\"primary\", \"secondary\", \"accent\", \"text\", \"muted\", \"background\"];\nconst FONT_ROLES = [\"heading\", \"body\", \"mono\"];\nconst MARGIN_SIDES = [\"top\", \"right\", \"bottom\", \"left\"];\nconst ADDRESS_PARTS = [\"line1\", \"line2\", \"postal_code\", \"city\", \"country\"];\nconst COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000};\nconst BANK_TEXT = {account_holder: 200, bank_name: 200};\nconst COMPANY_KEYS = [\"legal_name\", ...Object.keys(COMPANY_TEXT), \"address\", \"bank\"];\nconst BRAND_KEYS = [\"colors\", \"fonts\", \"logo\", \"page\"];\n\nfunction fail(code) { throw new Error(code); }\nfunction isObject(value) { return value !== null && typeof value === \"object\" && !Array.isArray(value); }\nfunction onlyKeys(value, allowed, name) { for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(name + \"_unknown_field\"); }\nfunction text(value, name, max, required) {\n if (value === undefined || value === null || value === \"\") { if (required) fail(name + \"_required\"); return \"\"; }\n if (typeof value !== \"string\" || value.length > max) fail(name + \"_invalid\");\n const trimmed = value.trim();\n if (required && !trimmed) fail(name + \"_required\");\n return trimmed;\n}\nfunction margin(value, name) {\n const raw = typeof value === \"number\" ? String(value) : value;\n if (typeof raw !== \"string\" || !/^[0-9]{1,3}(\\.[0-9]{1,2})?$/.test(raw.trim())) fail(name + \"_invalid\");\n const number = Number(raw.trim());\n if (number > 100) fail(name + \"_invalid\");\n return number;\n}\nfunction logoRef(value) {\n if (typeof value !== \"string\" || !/^storage:\\/\\/[^\\s]{1,500}$/.test(value) || value.includes(\"..\") || value.toLowerCase().includes(\"secret://\")) fail(\"logo_ref_invalid\");\n return value;\n}\n\n// Canonical body, the stored shape: { schema_version, company, brand }. company.logo is never stored: it is derived from brand.logo.ref on read.\nfunction normalizeBody(body) {\n if (!isObject(body) || body.schema_version !== 1) fail(\"body_schema_invalid\");\n onlyKeys(body, [\"schema_version\", \"company\", \"brand\"], \"body\");\n const c = body.company, b = body.brand;\n if (!isObject(c) || !isObject(b)) fail(\"body_schema_invalid\");\n if (c.logo !== undefined) fail(\"company_logo_derived_from_brand\");\n onlyKeys(c, COMPANY_KEYS, \"company\");\n const company = {legal_name: text(c.legal_name, \"legal_name\", 200, true)};\n for (const [key, max] of Object.entries(COMPANY_TEXT)) { const value = text(c[key], key, max, false); if (value) company[key] = value; }\n if (c.address !== undefined) {\n if (!isObject(c.address)) fail(\"address_invalid\");\n onlyKeys(c.address, ADDRESS_PARTS, \"address\");\n const address = {};\n for (const part of ADDRESS_PARTS) { const value = text(c.address[part], \"address_\" + part, 200, false); if (value) address[part] = value; }\n if (Object.keys(address).length) {\n for (const part of [\"line1\", \"postal_code\", \"city\", \"country\"]) if (!address[part]) fail(\"address_\" + part + \"_required\");\n company.address = address;\n }\n }\n if (c.bank !== undefined) {\n if (!isObject(c.bank)) fail(\"bank_invalid\");\n onlyKeys(c.bank, [\"account_holder\", \"iban\", \"bic\", \"bank_name\"], \"bank\");\n const bank = {};\n for (const [key, max] of Object.entries(BANK_TEXT)) { const value = text(c.bank[key], \"bank_\" + key, max, false); if (value) bank[key] = value; }\n if (c.bank.iban !== undefined && c.bank.iban !== \"\") {\n if (typeof c.bank.iban !== \"string\") fail(\"iban_invalid\");\n const iban = c.bank.iban.replace(/\\s+/g, \"\").toUpperCase();\n if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail(\"iban_invalid\");\n bank.iban = iban;\n }\n if (c.bank.bic !== undefined && c.bank.bic !== \"\") {\n if (typeof c.bank.bic !== \"string\") fail(\"bic_invalid\");\n const bic = c.bank.bic.replace(/\\s+/g, \"\").toUpperCase();\n if (!BIC.test(bic)) fail(\"bic_invalid\");\n bank.bic = bic;\n }\n if (Object.keys(bank).length) company.bank = bank;\n }\n onlyKeys(b, BRAND_KEYS, \"brand\");\n if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail(\"brand_invalid\");\n onlyKeys(b.colors, COLOR_TOKENS, \"colors\");\n onlyKeys(b.fonts, FONT_ROLES, \"fonts\");\n onlyKeys(b.logo, [\"ref\", \"alt\"], \"logo\");\n onlyKeys(b.page, [\"size\", \"margins_mm\"], \"page\");\n onlyKeys(b.page.margins_mm, MARGIN_SIDES, \"margins_mm\");\n const colors = {};\n for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== \"string\" || !COLOR.test(b.colors[token])) fail(\"color_\" + token + \"_invalid\"); colors[token] = b.colors[token]; }\n const fonts = {};\n for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail(\"font_\" + role + \"_invalid\"); onlyKeys(b.fonts[role], [\"family\"], \"font_\" + role); fonts[role] = {family: text(b.fonts[role].family, \"font_\" + role, 100, true)}; }\n if (b.page.size !== \"A4\" && b.page.size !== \"Letter\") fail(\"page_size_invalid\");\n const margins_mm = {};\n for (const side of MARGIN_SIDES) margins_mm[side] = margin(b.page.margins_mm[side], \"margin_\" + side);\n const brand = {colors, fonts, logo: {ref: logoRef(b.logo.ref), alt: text(b.logo.alt, \"logo_alt\", 200, true)}, page: {size: b.page.size, margins_mm}};\n return {schema_version: 1, company, brand};\n}\n\n// Flat form input -> structured body.\nfunction bodyFromFields(input) {\n if (!isObject(input)) fail(\"input_invalid\");\n const field = (name) => (input[name] === undefined || input[name] === null ? \"\" : input[name]);\n const company = {legal_name: field(\"legal_name\")};\n for (const key of Object.keys(COMPANY_TEXT)) if (field(key) !== \"\") company[key] = field(key);\n const address = {};\n for (const part of ADDRESS_PARTS) if (field(\"address_\" + part) !== \"\") address[part] = field(\"address_\" + part);\n if (Object.keys(address).length) company.address = address;\n const bank = {};\n if (field(\"bank_account_holder\") !== \"\") bank.account_holder = field(\"bank_account_holder\");\n if (field(\"bank_iban\") !== \"\") bank.iban = field(\"bank_iban\");\n if (field(\"bank_bic\") !== \"\") bank.bic = field(\"bank_bic\");\n if (field(\"bank_name\") !== \"\") bank.bank_name = field(\"bank_name\");\n if (Object.keys(bank).length) company.bank = bank;\n const colors = {};\n for (const token of COLOR_TOKENS) colors[token] = field(\"color_\" + token);\n const fonts = {};\n for (const role of FONT_ROLES) fonts[role] = {family: field(\"font_\" + role)};\n const margins_mm = {};\n for (const side of MARGIN_SIDES) margins_mm[side] = field(\"margin_\" + side);\n return {schema_version: 1, company, brand: {colors, fonts, logo: {ref: field(\"logo_ref\"), alt: field(\"logo_alt\")}, page: {size: field(\"page_size\"), margins_mm}}};\n}\n\n// Stored body -> flat strings, to prefill the form.\nfunction toFields(body) {\n const c = body.company, b = body.brand, a = c.address || {}, k = c.bank || {};\n const fields = {legal_name: c.legal_name, address_line1: a.line1 || \"\", address_line2: a.line2 || \"\", address_postal_code: a.postal_code || \"\", address_city: a.city || \"\", address_country: a.country || \"\", bank_account_holder: k.account_holder || \"\", bank_iban: k.iban || \"\", bank_bic: k.bic || \"\", bank_name: k.bank_name || \"\"};\n for (const key of Object.keys(COMPANY_TEXT)) fields[key] = c[key] || \"\";\n for (const token of COLOR_TOKENS) fields[\"color_\" + token] = b.colors[token];\n for (const role of FONT_ROLES) fields[\"font_\" + role] = b.fonts[role].family;\n fields.logo_ref = b.logo.ref; fields.logo_alt = b.logo.alt; fields.page_size = b.page.size;\n for (const side of MARGIN_SIDES) fields[\"margin_\" + side] = String(b.page.margins_mm[side]);\n return fields;\n}\n\n// The template/v1 context pair. The body maps onto company and brand as is; only company.logo is derived, from the single brand.logo source.\nfunction project(body) {\n const company = {...body.company};\n if (isObject(body.brand) && isObject(body.brand.logo) && typeof body.brand.logo.ref === \"string\" && body.brand.logo.ref !== \"\") company.logo = {ref: body.brand.logo.ref};\n return {company, brand: body.brand};\n}\n\nfunction deepEqual(a, b) {\n if (a === b) return true;\n if (!a || !b || typeof a !== \"object\" || typeof b !== \"object\" || Array.isArray(a) !== Array.isArray(b)) return false;\n const ka = Object.keys(a), kb = Object.keys(b);\n return ka.length === kb.length && ka.every((key) => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key]));\n}\n\n// A stored body must already be canonical: it is projected as it is, never rewritten (no trimming, no dropped or added key).\nfunction checkedBody(raw) {\n if (!deepEqual(normalizeBody(raw), raw)) fail(\"stored_body_not_canonical\");\n return raw;\n}\n\n// Only the broker's explicit not-found code (NOT_FOUND, \"application data record not found\") means \"no profile yet\".\nfunction brokerCode(value) {\n if (isObject(value) && isObject(value.error)) return typeof value.error.code === \"string\" ? value.error.code : \"unknown\";\n return null;\n}\nfunction isNotFound(error) { return isObject(error) && error.code === \"NOT_FOUND\"; }\nfunction brokerFailure(code) { return \"broker_error_\" + String(code || \"unknown\").toLowerCase().replace(/[^a-z0-9_]/g, \"_\"); }\n\nfunction luminance(hex) {\n const channel = (offset) => { const v = parseInt(hex.slice(offset, offset + 2), 16) / 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };\n return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5);\n}\nfunction contrast(a, b) { const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); return Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100; }\nfunction colorPreview(brand) {\n return COLOR_TOKENS.map((token) => ({token, hex: brand.colors[token], contrast_on_background: contrast(brand.colors[token], brand.colors.background)}));\n}\n\nfunction brokerRecord(response) {\n const code = brokerCode(response);\n if (code !== null) fail(brokerFailure(code));\n const payload = response && response.data ? response.data : response;\n const item = payload && payload.record;\n if (!item || item.namespace !== NAMESPACE || item.key !== RECORD_KEY) fail(\"broker_record_identity_invalid\");\n if (!Number.isSafeInteger(item.revision) || item.revision < 0) fail(\"broker_revision_invalid\");\n const p = item.permissions;\n if (!p || typeof p.can_read !== \"boolean\" || typeof p.can_write !== \"boolean\" || typeof p.can_manage !== \"boolean\") fail(\"broker_permissions_invalid\");\n return item;\n}\n\nlet response, missing = false;\ntry {\n response = await callTool(\"recipe--application_data_v1\", {operation: \"read\", namespace: NAMESPACE, record_key: RECORD_KEY});\n} catch (error) {\n if (isNotFound(error)) missing = true; else throw error;\n}\nif (!missing) {\n const code = brokerCode(response);\n if (code === \"NOT_FOUND\") missing = true; else if (code !== null) fail(brokerFailure(code));\n}\nif (missing) {\n return {found: false, namespace: NAMESPACE, record_key: RECORD_KEY, revision: 0, owner_user_id: \"\", permissions: {can_read: false, can_write: false, can_manage: false}, body: null, profile: null, color_preview: [], fields: {}, message: \"No company profile saved yet. Save one with expected revision 0.\", effects: [{type: \"open_form\", payload: {form_id: \"save\", submit_event: \"save\", prefill: {expected_revision: \"0\", page_size: \"A4\", confirmation_manuelle: \"false\"}}}], external_effect: false};\n}\nconst item = brokerRecord(response);\nconst body = checkedBody(item.data);\nconst fields = toFields(body);\nreturn {found: true, namespace: NAMESPACE, record_key: RECORD_KEY, revision: item.revision, owner_user_id: typeof item.owner_user_id === \"string\" ? item.owner_user_id : \"\", permissions: item.permissions, body, profile: project(body), color_preview: colorPreview(body.brand), fields, message: \"Company profile read. The projection is ready for template/v1.\", effects: [{type: \"open_form\", payload: {form_id: \"save\", submit_event: \"save\", prefill: {...fields, expected_revision: String(item.revision), confirmation_manuelle: \"false\"}}}], external_effect: false};", + "output_key": "result" + } + ], + "output": { + "found": "{{ result.found }}", + "namespace": "{{ result.namespace }}", + "record_key": "{{ result.record_key }}", + "revision": "{{ result.revision }}", + "owner_user_id": "{{ result.owner_user_id }}", + "permissions": "{{ result.permissions }}", + "body": "{{ result.body }}", + "profile": "{{ result.profile }}", + "color_preview": "{{ result.color_preview }}", + "fields": "{{ result.fields }}", + "effects": "{{ result.effects }}", + "message": "{{ result.message }}", + "external_effect": false + } +} diff --git a/profile/module.yaml b/profile/module.yaml new file mode 100644 index 0000000..2af70b6 --- /dev/null +++ b/profile/module.yaml @@ -0,0 +1,31 @@ +{ + "$schema": "agentmaurice.module/v2", + "schema_version": 2, + "key": "cib-profile", + "name": "Company-in-a-Box — company profile", + "version": "0.1.0", + "provides": { + "actions": [ + { + "key": "save", + "workflow_id": "cib-admin-profile-save", + "workflow_version": "1" + } + ], + "queries": [ + { + "key": "read", + "workflow_id": "cib-profile-read", + "workflow_version": "1" + } + ], + "apps": [ + { + "key": "profile-console", + "miniapp_id": "cib-profile-console", + "miniapp_version": "1" + } + ] + }, + "requires": {} +} diff --git a/scripts/inventory.py b/scripts/inventory.py index 77d9898..ea6c43c 100644 --- a/scripts/inventory.py +++ b/scripts/inventory.py @@ -48,6 +48,8 @@ NATIVE = { 'image-studio': {'generators': ['tooling/image-studio/build.py'], 'language': 'English source', 'publication': 'native to this repository, unpublished'}, + 'profile': {'generators': ['tooling/profile/build.py', 'tooling/profile/compose.py'], + 'language': 'English source', 'publication': 'native to this repository, unpublished'}, } CONSUMERS = { 'watch-memory': ['watch', 'company-memory'], 'content-memory': ['content', 'company-memory'], diff --git a/scripts/test.py b/scripts/test.py index a5641c8..1e93eb9 100644 --- a/scripts/test.py +++ b/scripts/test.py @@ -3,7 +3,7 @@ import os, shutil, subprocess, sys, tempfile from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -PYTHON_SUITES = ['templates/company-in-a-box/tests'] + [f'tooling/{name}/tests' for name in ('company-memory', 'memory-integration', 'daily-routine', 'work-cases', 'enterprise-admin', 'marketing-launch', 'image-studio', 'catalog')] +PYTHON_SUITES = ['templates/company-in-a-box/tests'] + [f'tooling/{name}/tests' for name in ('company-memory', 'memory-integration', 'daily-routine', 'work-cases', 'enterprise-admin', 'marketing-launch', 'image-studio', 'profile', 'catalog')] NODE_TESTS = [f'tooling/{path}' for path in ('memory-integration/tests/test_publication.mjs', 'daily-routine/tests/metrics.test.mjs', 'work-cases/tests/domain.test.mjs', 'marketing-launch/tests/test_domain.cjs', 'marketing-launch/tests/test_generated_runtime.cjs')] def main(): env = {**os.environ, 'PYTHONDONTWRITEBYTECODE': '1'} @@ -18,7 +18,7 @@ def main(): subprocess.run([sys.executable, '-m', 'unittest', 'discover', '-s', str(work / name), '-p', 'test_*.py', '-v'], env=env, cwd=work, check=True) for name in NODE_TESTS: subprocess.run(['node', str(work / name)], env=env, cwd=work, check=True) - for name in ('work-cases', 'daily-routine', 'enterprise-admin', 'marketing-launch', 'image-studio'): + for name in ('work-cases', 'daily-routine', 'enterprise-admin', 'marketing-launch', 'image-studio', 'profile'): module = work / name before = {p.relative_to(module): p.read_bytes() for p in module.rglob('*') if p.is_file()} extras = [work / 'templates/company-in-a-box/tests/marketing-launch-plan.json', work / 'tooling/marketing-launch/service-gates.json'] if name == 'marketing-launch' else [] @@ -28,5 +28,5 @@ def main(): if before != after or any(p.read_bytes() != data for p, data in extra_before.items()): raise SystemExit(f'{name}: le générateur ne reproduit pas les ressources publiées') - print('PASS: 9 suites unittest, contrat ACL Python et 5 contrôles Node et 5 reconstructions à octets identiques, sans réseau ni runtime.') + print('PASS: 10 suites unittest, contrat ACL Python et 5 contrôles Node et 6 reconstructions à octets identiques, sans réseau ni runtime.') if __name__ == '__main__': main() diff --git a/tooling/profile/README.md b/tooling/profile/README.md new file mode 100644 index 0000000..dad3f24 --- /dev/null +++ b/tooling/profile/README.md @@ -0,0 +1,114 @@ +# Company profile — cib-profile 0.1.0 + +The company profile is the identity and brand of a company, entered once and +used by every generated document: legal name, trade name, legal form, capital, +SIREN/SIRET, VAT number, RCS, address, contact details, legal mentions, +optional bank details, and the brand (six colours, three font families, a logo +reference and the page size and margins). The Module stores it as **one +Application record** and projects it as the `{ company, brand }` pair of the +`agentmaurice.template/v1` contract. + +| Item | Value | +|---|---| +| Module key | `cib-profile` (directory `profile`) | +| Record | namespace `cib-profile`, key `company-profile`, through `recipe--application_data_v1` | +| Query `read` | Workflow `cib-profile-read`: the body, the `{ company, brand }` projection, a colour preview, the revision and the permissions | +| Action `save` | Workflow `cib-admin-profile-save`: save with `expected_revision`, `cib_admin` only, `confirmation_manuelle` = `true` | +| App `profile-console` | MiniApp `cib-profile-console`: company and brand fields, colour preview, logo by `storage://` reference | + +## Stored body and projection + +The body is `{ "schema_version": 1, "company": {...}, "brand": {...} }`. It maps +onto the contract without transformation: `body.company` is `company` and +`body.brand` is `brand` (`tokens.schema.json`). The only derived value is +`company.logo`, set at read time to `{ "ref": brand.logo.ref }`. The logo has a +**single source**, `brand.logo` (`ref` and `alt`); a body that carries its own +`company.logo` is refused. `company.bank` (`account_holder`, `iban`, `bic`, +`bank_name`) is optional. IBAN and BIC are normalised (upper case, no spaces) +and checked by shape (15 to 34 characters for the IBAN); no check digit is +computed. + +The save Workflow validates strictly and the read Workflow validates the stored +body again, so a record written by something else is refused rather than +projected. A stored body is projected as it is, never rewritten: if it is not already canonical +(trimmed, no empty value, IBAN and BIC normalised) the read fails with +`stored_body_not_canonical`. The projection adds nothing but `company.logo`. A save needs an explicit `expected_revision` (`0` to create); a +conflict is the broker's answer and is not retried. + +## Contract copy + +`contract/` holds a frozen, byte-for-byte copy of `namespaces.schema.json` and +`tokens.schema.json` (including `company.bank`), pinned in `contract/PIN.json` +by SHA-256 and by the commit of the contract repository that introduced them. +The tests validate the fixtures and every projection against this copy. To +follow a contract change, copy the new files in a reviewed change and update the +pin; the SHA-256 values are authoritative if the source commit is rewritten. + +## Roles + +Workflow roles live in the published Application surface, not in the manifest, +and the platform checks them at admission; the broker revalidates the required +role. The Workflow code receives no caller identity and cannot check a role +itself, so it ignores any role sent in its input. A person who has write access +to the record but not the `cib_admin` role is refused only if the surface says so. + +`compose.py --write` therefore also writes a **surface draft**, +`/surface-drafts/cib-profile.surface-draft.json`, that carries +`required_role: cib_admin` explicitly on `cib-admin-profile-save` (from +`service-gates.json`) and none on `cib-profile-read`. Merge it into the surface +you review, then publish the surface yourself; compose publishes nothing and +refuses a divergent existing draft. The `cib-admin-` name still lets +`tooling/enterprise-admin/service_roles.py` agree, but the gate no longer +depends on that convention. The role, the form confirmation and the broker ACL +are cumulative; none replaces another, and the identity comes from the server. + +## How document-studio reads the profile + +`document-studio` calls `recipe--application_data_v1` with operation `read`, +namespace `cib-profile` and key `company-profile`, then uses `company` and `brand` +of the projection (or calls the `read` query). Its Agent therefore needs the +namespace `cib-profile` in its allowlist for that broker, and the person running +the generation needs read access on the record. A saved profile is not touched +by the studio. + +## Limits + +- **Broker not wired (AGENT-1305).** `recipe--application_data_v1` is not wired + in the One yet. This Module is code and offline tests on fixtures: it has not + run on a One. Only the broker's explicit `NOT_FOUND` code (taken from the + unmerged AGENT-1305 broker source, not from the wiki, which names none) means + "no profile yet"; `permission_denied`, an empty or record-less response and any + other error are explicit errors. How the sandbox surfaces that code is to be + qualified when the broker exists. +- **Sharing is per person.** A record is private to its owner until the owner or + a recovery administrator shares it with each person (`read` or `write`). There + is no "everyone in the company" read with the current broker, and this Module + does not work around it. `cib-admin-record-share` lists only four historical + namespaces, so `cib-profile` is not shareable through it today either. + Until a per-company read exists, a document is generated by a person who can + read the record. +- **No logo upload.** The logo is a `storage://` reference to a file that is + already in Storage. Uploading or converting a logo is out of scope. +- **No legal format.** No Factur-X or Peppol format is produced or validated. Bank + details and identifiers are stored and projected as entered, checked by shape + only. +- **Colour preview** is a table (token, hex, contrast against the background); + no swatch component is used. + +## Composition and tests + +```sh +python3 tooling/profile/build.py +python3 tooling/profile/compose.py --consumer-dir /path/to/consumer --owner-alias admin +python3 tooling/profile/compose.py --consumer-dir /path/to/consumer --owner-alias admin --write +``` + +`build.py` generates the three resources and `module.yaml`; `compose.py` plans +or copies them under a consumer Agent, writes the surface draft with the explicit role gate, and refuses a divergent file. The tests +(`tooling/profile/tests`) run the Workflow code under Node with a mocked broker +on synthetic fixtures; they use a small built-in JSON Schema validator, so no +extra package is needed. Passing them is not a runtime qualification: after +installation, qualify the parcours (save, read, revision conflict, share and +revocation) on a separate One with fictitious data. + +See [security boundaries](../../docs/SECURITY.md) and [tests](../../docs/TESTING.md). diff --git a/tooling/profile/build.py b/tooling/profile/build.py new file mode 100644 index 0000000..8ea088f --- /dev/null +++ b/tooling/profile/build.py @@ -0,0 +1,379 @@ +#!/usr/bin/env python3 +"""Generate the cib-profile Module: the company profile (company and brand) kept in an Application record. + +The Module reads and saves one record, namespace `cib-profile`, key `company-profile`, through the native +`recipe--application_data_v1` broker, and projects it as the `{company, brand}` pair of the template/v1 contract. +Nothing here is executed by the generator; the Workflows run in the One once the broker is wired (AGENT-1305). +""" +from __future__ import annotations + +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +MODULE_DIR = ROOT.parents[1] / "profile" +DEST = MODULE_DIR / "agents" / "main" + +NAMESPACE = "cib-profile" +RECORD_KEY = "company-profile" +BROKER = "recipe--application_data_v1" + +# Flat form fields, in display order: (name, title, kind, required). Selects are added separately. +COMPANY_FIELDS = [ + ("legal_name", "Legal name", "string", True), + ("trade_name", "Trade name", "string", False), + ("legal_form", "Legal form", "string", False), + ("share_capital", "Share capital", "string", False), + ("siren", "SIREN", "string", False), + ("siret", "SIRET", "string", False), + ("vat_number", "VAT number", "string", False), + ("rcs", "Trade register (RCS)", "string", False), + ("address_line1", "Address, line 1", "string", False), + ("address_line2", "Address, line 2", "string", False), + ("address_postal_code", "Postal code", "string", False), + ("address_city", "City", "string", False), + ("address_country", "Country", "string", False), + ("email", "E-mail", "string", False), + ("phone", "Phone", "string", False), + ("website", "Website", "string", False), + ("legal_mentions", "Legal mentions", "text", False), + ("bank_account_holder", "Bank account holder", "string", False), + ("bank_iban", "IBAN", "string", False), + ("bank_bic", "BIC", "string", False), + ("bank_name", "Bank name", "string", False), +] +BRAND_FIELDS = [ + ("color_primary", "Primary colour (#RRGGBB)", "string", True), + ("color_secondary", "Secondary colour (#RRGGBB)", "string", True), + ("color_accent", "Accent colour (#RRGGBB)", "string", True), + ("color_text", "Text colour (#RRGGBB)", "string", True), + ("color_muted", "Muted colour (#RRGGBB)", "string", True), + ("color_background", "Background colour (#RRGGBB)", "string", True), + ("font_heading", "Heading font family", "string", True), + ("font_body", "Body font family", "string", True), + ("font_mono", "Monospace font family", "string", True), + ("logo_ref", "Logo reference (storage://...)", "string", True), + ("logo_alt", "Logo alternative text", "string", True), + ("margin_top", "Top margin (mm)", "string", True), + ("margin_right", "Right margin (mm)", "string", True), + ("margin_bottom", "Bottom margin (mm)", "string", True), + ("margin_left", "Left margin (mm)", "string", True), +] +ALL_FIELD_NAMES = [f[0] for f in COMPANY_FIELDS] + [f[0] for f in BRAND_FIELDS] + ["page_size"] + +# Shared JavaScript (Deno sandbox). It never contains a double-brace sequence: the Workflow engine would read it +# as a template action. Validation is strict and canonical; a stored body is re-validated on every read. +LIB = r''' +const NAMESPACE = "cib-profile"; +const RECORD_KEY = "company-profile"; +const COLOR = /^#[0-9a-fA-F]{6}$/; +const IBAN = /^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$/; +const BIC = /^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$/; +const COLOR_TOKENS = ["primary", "secondary", "accent", "text", "muted", "background"]; +const FONT_ROLES = ["heading", "body", "mono"]; +const MARGIN_SIDES = ["top", "right", "bottom", "left"]; +const ADDRESS_PARTS = ["line1", "line2", "postal_code", "city", "country"]; +const COMPANY_TEXT = {trade_name: 200, legal_form: 100, share_capital: 100, siren: 32, siret: 32, vat_number: 32, rcs: 200, email: 254, phone: 64, website: 300, legal_mentions: 4000}; +const BANK_TEXT = {account_holder: 200, bank_name: 200}; +const COMPANY_KEYS = ["legal_name", ...Object.keys(COMPANY_TEXT), "address", "bank"]; +const BRAND_KEYS = ["colors", "fonts", "logo", "page"]; + +function fail(code) { throw new Error(code); } +function isObject(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } +function onlyKeys(value, allowed, name) { for (const key of Object.keys(value)) if (!allowed.includes(key)) fail(name + "_unknown_field"); } +function text(value, name, max, required) { + if (value === undefined || value === null || value === "") { if (required) fail(name + "_required"); return ""; } + if (typeof value !== "string" || value.length > max) fail(name + "_invalid"); + const trimmed = value.trim(); + if (required && !trimmed) fail(name + "_required"); + return trimmed; +} +function margin(value, name) { + const raw = typeof value === "number" ? String(value) : value; + if (typeof raw !== "string" || !/^[0-9]{1,3}(\.[0-9]{1,2})?$/.test(raw.trim())) fail(name + "_invalid"); + const number = Number(raw.trim()); + if (number > 100) fail(name + "_invalid"); + return number; +} +function logoRef(value) { + if (typeof value !== "string" || !/^storage:\/\/[^\s]{1,500}$/.test(value) || value.includes("..") || value.toLowerCase().includes("secret://")) fail("logo_ref_invalid"); + return value; +} + +// Canonical body, the stored shape: { schema_version, company, brand }. company.logo is never stored: it is derived from brand.logo.ref on read. +function normalizeBody(body) { + if (!isObject(body) || body.schema_version !== 1) fail("body_schema_invalid"); + onlyKeys(body, ["schema_version", "company", "brand"], "body"); + const c = body.company, b = body.brand; + if (!isObject(c) || !isObject(b)) fail("body_schema_invalid"); + if (c.logo !== undefined) fail("company_logo_derived_from_brand"); + onlyKeys(c, COMPANY_KEYS, "company"); + const company = {legal_name: text(c.legal_name, "legal_name", 200, true)}; + for (const [key, max] of Object.entries(COMPANY_TEXT)) { const value = text(c[key], key, max, false); if (value) company[key] = value; } + if (c.address !== undefined) { + if (!isObject(c.address)) fail("address_invalid"); + onlyKeys(c.address, ADDRESS_PARTS, "address"); + const address = {}; + for (const part of ADDRESS_PARTS) { const value = text(c.address[part], "address_" + part, 200, false); if (value) address[part] = value; } + if (Object.keys(address).length) { + for (const part of ["line1", "postal_code", "city", "country"]) if (!address[part]) fail("address_" + part + "_required"); + company.address = address; + } + } + if (c.bank !== undefined) { + if (!isObject(c.bank)) fail("bank_invalid"); + onlyKeys(c.bank, ["account_holder", "iban", "bic", "bank_name"], "bank"); + const bank = {}; + for (const [key, max] of Object.entries(BANK_TEXT)) { const value = text(c.bank[key], "bank_" + key, max, false); if (value) bank[key] = value; } + if (c.bank.iban !== undefined && c.bank.iban !== "") { + if (typeof c.bank.iban !== "string") fail("iban_invalid"); + const iban = c.bank.iban.replace(/\s+/g, "").toUpperCase(); + if (iban.length < 15 || iban.length > 34 || !IBAN.test(iban)) fail("iban_invalid"); + bank.iban = iban; + } + if (c.bank.bic !== undefined && c.bank.bic !== "") { + if (typeof c.bank.bic !== "string") fail("bic_invalid"); + const bic = c.bank.bic.replace(/\s+/g, "").toUpperCase(); + if (!BIC.test(bic)) fail("bic_invalid"); + bank.bic = bic; + } + if (Object.keys(bank).length) company.bank = bank; + } + onlyKeys(b, BRAND_KEYS, "brand"); + if (!isObject(b.colors) || !isObject(b.fonts) || !isObject(b.logo) || !isObject(b.page) || !isObject(b.page.margins_mm)) fail("brand_invalid"); + onlyKeys(b.colors, COLOR_TOKENS, "colors"); + onlyKeys(b.fonts, FONT_ROLES, "fonts"); + onlyKeys(b.logo, ["ref", "alt"], "logo"); + onlyKeys(b.page, ["size", "margins_mm"], "page"); + onlyKeys(b.page.margins_mm, MARGIN_SIDES, "margins_mm"); + const colors = {}; + for (const token of COLOR_TOKENS) { if (typeof b.colors[token] !== "string" || !COLOR.test(b.colors[token])) fail("color_" + token + "_invalid"); colors[token] = b.colors[token]; } + const fonts = {}; + for (const role of FONT_ROLES) { if (!isObject(b.fonts[role])) fail("font_" + role + "_invalid"); onlyKeys(b.fonts[role], ["family"], "font_" + role); fonts[role] = {family: text(b.fonts[role].family, "font_" + role, 100, true)}; } + if (b.page.size !== "A4" && b.page.size !== "Letter") fail("page_size_invalid"); + const margins_mm = {}; + for (const side of MARGIN_SIDES) margins_mm[side] = margin(b.page.margins_mm[side], "margin_" + side); + const brand = {colors, fonts, logo: {ref: logoRef(b.logo.ref), alt: text(b.logo.alt, "logo_alt", 200, true)}, page: {size: b.page.size, margins_mm}}; + return {schema_version: 1, company, brand}; +} + +// Flat form input -> structured body. +function bodyFromFields(input) { + if (!isObject(input)) fail("input_invalid"); + const field = (name) => (input[name] === undefined || input[name] === null ? "" : input[name]); + const company = {legal_name: field("legal_name")}; + for (const key of Object.keys(COMPANY_TEXT)) if (field(key) !== "") company[key] = field(key); + const address = {}; + for (const part of ADDRESS_PARTS) if (field("address_" + part) !== "") address[part] = field("address_" + part); + if (Object.keys(address).length) company.address = address; + const bank = {}; + if (field("bank_account_holder") !== "") bank.account_holder = field("bank_account_holder"); + if (field("bank_iban") !== "") bank.iban = field("bank_iban"); + if (field("bank_bic") !== "") bank.bic = field("bank_bic"); + if (field("bank_name") !== "") bank.bank_name = field("bank_name"); + if (Object.keys(bank).length) company.bank = bank; + const colors = {}; + for (const token of COLOR_TOKENS) colors[token] = field("color_" + token); + const fonts = {}; + for (const role of FONT_ROLES) fonts[role] = {family: field("font_" + role)}; + const margins_mm = {}; + for (const side of MARGIN_SIDES) margins_mm[side] = field("margin_" + side); + return {schema_version: 1, company, brand: {colors, fonts, logo: {ref: field("logo_ref"), alt: field("logo_alt")}, page: {size: field("page_size"), margins_mm}}}; +} + +// Stored body -> flat strings, to prefill the form. +function toFields(body) { + const c = body.company, b = body.brand, a = c.address || {}, k = c.bank || {}; + const fields = {legal_name: c.legal_name, address_line1: a.line1 || "", address_line2: a.line2 || "", address_postal_code: a.postal_code || "", address_city: a.city || "", address_country: a.country || "", bank_account_holder: k.account_holder || "", bank_iban: k.iban || "", bank_bic: k.bic || "", bank_name: k.bank_name || ""}; + for (const key of Object.keys(COMPANY_TEXT)) fields[key] = c[key] || ""; + for (const token of COLOR_TOKENS) fields["color_" + token] = b.colors[token]; + for (const role of FONT_ROLES) fields["font_" + role] = b.fonts[role].family; + fields.logo_ref = b.logo.ref; fields.logo_alt = b.logo.alt; fields.page_size = b.page.size; + for (const side of MARGIN_SIDES) fields["margin_" + side] = String(b.page.margins_mm[side]); + return fields; +} + +// The template/v1 context pair. The body maps onto company and brand as is; only company.logo is derived, from the single brand.logo source. +function project(body) { + const company = {...body.company}; + if (isObject(body.brand) && isObject(body.brand.logo) && typeof body.brand.logo.ref === "string" && body.brand.logo.ref !== "") company.logo = {ref: body.brand.logo.ref}; + return {company, brand: body.brand}; +} + +function deepEqual(a, b) { + if (a === b) return true; + if (!a || !b || typeof a !== "object" || typeof b !== "object" || Array.isArray(a) !== Array.isArray(b)) return false; + const ka = Object.keys(a), kb = Object.keys(b); + return ka.length === kb.length && ka.every((key) => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key])); +} + +// A stored body must already be canonical: it is projected as it is, never rewritten (no trimming, no dropped or added key). +function checkedBody(raw) { + if (!deepEqual(normalizeBody(raw), raw)) fail("stored_body_not_canonical"); + return raw; +} + +// Only the broker's explicit not-found code (NOT_FOUND, "application data record not found") means "no profile yet". +function brokerCode(value) { + if (isObject(value) && isObject(value.error)) return typeof value.error.code === "string" ? value.error.code : "unknown"; + return null; +} +function isNotFound(error) { return isObject(error) && error.code === "NOT_FOUND"; } +function brokerFailure(code) { return "broker_error_" + String(code || "unknown").toLowerCase().replace(/[^a-z0-9_]/g, "_"); } + +function luminance(hex) { + const channel = (offset) => { const v = parseInt(hex.slice(offset, offset + 2), 16) / 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }; + return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5); +} +function contrast(a, b) { const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); return Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100; } +function colorPreview(brand) { + return COLOR_TOKENS.map((token) => ({token, hex: brand.colors[token], contrast_on_background: contrast(brand.colors[token], brand.colors.background)})); +} + +function brokerRecord(response) { + const code = brokerCode(response); + if (code !== null) fail(brokerFailure(code)); + const payload = response && response.data ? response.data : response; + const item = payload && payload.record; + if (!item || item.namespace !== NAMESPACE || item.key !== RECORD_KEY) fail("broker_record_identity_invalid"); + if (!Number.isSafeInteger(item.revision) || item.revision < 0) fail("broker_revision_invalid"); + const p = item.permissions; + if (!p || typeof p.can_read !== "boolean" || typeof p.can_write !== "boolean" || typeof p.can_manage !== "boolean") fail("broker_permissions_invalid"); + return item; +} +''' + +READ_CODE = "import { callTool } from './tools/nats_bridge.ts';\n" + LIB + r''' +let response, missing = false; +try { + response = await callTool("recipe--application_data_v1", {operation: "read", namespace: NAMESPACE, record_key: RECORD_KEY}); +} catch (error) { + if (isNotFound(error)) missing = true; else throw error; +} +if (!missing) { + const code = brokerCode(response); + if (code === "NOT_FOUND") missing = true; else if (code !== null) fail(brokerFailure(code)); +} +if (missing) { + return {found: false, namespace: NAMESPACE, record_key: RECORD_KEY, revision: 0, owner_user_id: "", permissions: {can_read: false, can_write: false, can_manage: false}, body: null, profile: null, color_preview: [], fields: {}, message: "No company profile saved yet. Save one with expected revision 0.", effects: [{type: "open_form", payload: {form_id: "save", submit_event: "save", prefill: {expected_revision: "0", page_size: "A4", confirmation_manuelle: "false"}}}], external_effect: false}; +} +const item = brokerRecord(response); +const body = checkedBody(item.data); +const fields = toFields(body); +return {found: true, namespace: NAMESPACE, record_key: RECORD_KEY, revision: item.revision, owner_user_id: typeof item.owner_user_id === "string" ? item.owner_user_id : "", permissions: item.permissions, body, profile: project(body), color_preview: colorPreview(body.brand), fields, message: "Company profile read. The projection is ready for template/v1.", effects: [{type: "open_form", payload: {form_id: "save", submit_event: "save", prefill: {...fields, expected_revision: String(item.revision), confirmation_manuelle: "false"}}}], external_effect: false};''' + +SAVE_CODE = "import { callTool } from './tools/nats_bridge.ts';\nconst input = {{ json . }};\n" + LIB + r''' +const confirmed = input.confirmation_manuelle === true || input.confirmation_manuelle === "true"; +if (!confirmed) fail("manual_confirmation_required"); +let expected_revision = input.expected_revision; +if (expected_revision === undefined || expected_revision === null || expected_revision === "") fail("expected_revision_required"); +if (typeof expected_revision === "string" && /^[0-9]+$/.test(expected_revision)) expected_revision = Number(expected_revision); +if (!Number.isSafeInteger(expected_revision) || expected_revision < 0) fail("expected_revision_invalid"); +const body = normalizeBody(bodyFromFields(input)); +const response = await callTool("recipe--application_data_v1", {operation: "save", namespace: NAMESPACE, record_key: RECORD_KEY, data: body, expected_revision}); +const item = brokerRecord(response); +const stored = checkedBody(item.data); +return {namespace: NAMESPACE, record_key: RECORD_KEY, revision: item.revision, owner_user_id: typeof item.owner_user_id === "string" ? item.owner_user_id : "", permissions: item.permissions, shares: Array.isArray(item.shares) ? item.shares.length : 0, profile: project(stored), color_preview: colorPreview(stored.brand), message: "Company profile saved in the internal ACL store; no external effect. Other people read it only after an explicit per-person share.", external_effect: false};''' + + +def dump(path: Path, value: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + +def field(name: str, title: str, kind: str, required: bool, options=None, default=None) -> dict: + result = {"name": name, "title": title, "type": kind, "required": required} + if options: + result["options"] = [{"value": value, "label": label} for value, label in options] + if default is not None: + result["default"] = default + return result + + +def read_workflow() -> dict: + return { + "$schema": "agentmaurice.workflow/v2", "schema_version": 2, "kind": "workflow", + "workflow_id": "cib-profile-read", "version": "1", + "title": "Company profile — read", + "description": "Reads the company profile record (namespace cib-profile, key company-profile) through the native broker and returns the body with the { company, brand } projection for template/v1. It needs read access on the record; it never reads another person's data.", + "actions": [{"id": "read", "type": "code_execution", "context": {"allowed_tools": [BROKER]}, "code": READ_CODE, "output_key": "result"}], + "output": {key: "{{ result.%s }}" % key for key in ("found", "namespace", "record_key", "revision", "owner_user_id", "permissions", "body", "profile", "color_preview", "fields", "effects", "message")} | {"external_effect": False}, + } + + +def save_workflow() -> dict: + fields = [field(n, t, k, r) for n, t, k, r in COMPANY_FIELDS] + for n, t, k, r in BRAND_FIELDS: + if n == "margin_top": + fields.append(field("page_size", "Page size", "select", True, [("A4", "A4"), ("Letter", "Letter")], "A4")) + fields.append(field(n, t, k, r)) + for f in fields: + if f["name"] in ALL_FIELD_NAMES and "default" not in f: + f["default"] = "{{ state.profile.fields.%s }}" % f["name"] + fields.append(field("expected_revision", "Expected revision (0 to create)", "string", True, default="{{ state.profile.revision }}")) + fields.append(field("confirmation_manuelle", "Manual confirmation", "select", True, [("false", "No"), ("true", "Yes")], "false")) + return { + "$schema": "agentmaurice.workflow/v2", "schema_version": 2, "kind": "workflow", + "workflow_id": "cib-admin-profile-save", "version": "1", + "title": "Company profile — save", + "description": "Saves the company profile with an expected revision. Restricted to the cib_admin role (the cib-admin- prefix is what tooling/enterprise-admin/service_roles.py maps to it) and to a manual confirmation. The logo is a storage:// reference; there is no upload. Bank details are optional and checked by shape only.", + "forms": [{"id": "save", "title": "Company profile — save", "fields": fields, "actions_on_submit": ["save"]}], + "actions": [{"id": "save", "type": "code_execution", "context": {"allowed_tools": [BROKER]}, "code": SAVE_CODE, "output_key": "result"}], + "output": {key: "{{ result.%s }}" % key for key in ("namespace", "record_key", "revision", "owner_user_id", "permissions", "shares", "profile", "color_preview", "message")} | {"external_effect": False}, + } + + +def console() -> dict: + state_fields = ALL_FIELD_NAMES + ["expected_revision", "confirmation_manuelle"] + initial = {name: "" for name in state_fields} + initial.update({"page_size": "A4", "expected_revision": "0", "confirmation_manuelle": "false"}) + initial["profile"] = {"found": False, "revision": 0, "color_preview": [], "fields": {}, "message": "No profile loaded."} + initial["result"] = {"message": "No action."} + save_input = {name: "{{ state.%s }}" % name for name in state_fields} + return { + "$schema": "agentmaurice.miniapp/v2", "schema_version": 2, "kind": "miniapp", + "miniapp_id": "cib-profile-console", "version": "1", + "title": "Company profile", + "description": "Edit the company profile (identity, address, optional bank details, colours, fonts, logo reference and page margins) used by generated documents. One record, saved by a cib_admin with a manual confirmation.", + "ui": {"renderer": "component", "component": "company-in-a-box", "configuration": {"layout": [ + {"type": "callout", "title": "Company profile", "tone": "info", "value": "One shared profile for your documents. Load it, check the colour preview, then open the form \"Company profile - save\" in the available interactions. The logo is a storage:// reference to a file already in Storage; uploading a logo is not available here."}, + {"type": "button", "label": "Load the company profile", "on_click": "read"}, + {"type": "section", "title": "Current record", "children": [ + {"type": "stat", "label": "Revision", "value": {"state": "profile.revision"}}, + {"type": "stat", "label": "Legal name", "value": {"state": "profile.fields.legal_name"}}, + {"type": "stat", "label": "Logo reference", "value": {"state": "profile.fields.logo_ref"}}, + {"type": "text", "value": {"state": "profile.message"}}]}, + {"type": "section", "title": "Colour preview", "children": [ + {"type": "table", "columns": ["token", "hex", "contrast_on_background"], "column_labels": {"token": "Token", "hex": "Colour", "contrast_on_background": "Contrast on background"}, "rows": {"state": "profile.color_preview"}}]}, + {"type": "section", "title": "Last save", "children": [ + {"type": "text", "value": {"state": "result.message"}}, + {"type": "table", "columns": ["token", "hex", "contrast_on_background"], "column_labels": {"token": "Token", "hex": "Colour", "contrast_on_background": "Contrast on background"}, "rows": {"state": "result.color_preview"}}]}, + ]}}, + "state_schema": {"type": "object", "properties": {**{name: {"type": "string"} for name in state_fields}, "profile": {"type": "object"}, "result": {"type": "object"}}}, + "initial_state": initial, + "events": [ + {"event_id": "read", "trigger": "action.click", "workflow": {"workflow_id": "cib-profile-read", "input": {}}, "result_to_state": "profile"}, + {"event_id": "save", "trigger": "form.submit", "workflow": {"workflow_id": "cib-admin-profile-save", "input": save_input}, "result_to_state": "result"}, + ], + } + + +def manifest() -> dict: + return {"$schema": "agentmaurice.module/v2", "schema_version": 2, "key": "cib-profile", + "name": "Company-in-a-Box — company profile", "version": "0.1.0", + "provides": { + "actions": [{"key": "save", "workflow_id": "cib-admin-profile-save", "workflow_version": "1"}], + "queries": [{"key": "read", "workflow_id": "cib-profile-read", "workflow_version": "1"}], + "apps": [{"key": "profile-console", "miniapp_id": "cib-profile-console", "miniapp_version": "1"}]}, + "requires": {}} + + +def build() -> None: + dump(DEST / "workflows/cib-profile-read.json", read_workflow()) + dump(DEST / "workflows/cib-admin-profile-save.json", save_workflow()) + dump(DEST / "miniapps/cib-profile-console.json", console()) + dump(MODULE_DIR / "module.yaml", manifest()) + + +if __name__ == "__main__": + build() diff --git a/tooling/profile/compose.py b/tooling/profile/compose.py new file mode 100644 index 0000000..5a85eed --- /dev/null +++ b/tooling/profile/compose.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Dry-run composer for the profile Module resources; refuses divergence from a consumer Agent's files.""" +from __future__ import annotations +import argparse, hashlib, json, re, shutil +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +MODULE = ROOT.parents[1] / "profile" +RESOURCE_COUNT = 3 +GATES = ROOT / "service-gates.json" +DRAFT_DIR = "surface-drafts" +DRAFT_NAME = "cib-profile.surface-draft.json" + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def compose(consumer: Path, owner_alias: str = "admin"): + """Plan the copy of the Module resources under the consumer Agent; an existing different file is a conflict.""" + if not re.fullmatch(r"[a-z][a-z0-9_-]{0,63}", owner_alias): + raise ValueError("invalid owner alias") + spec = json.loads((consumer / "agents" / owner_alias / "agent-spec.json").read_text(encoding="utf-8")) + if spec.get("schema_version") != 2 or spec.get("agent_alias") != owner_alias or not re.fullmatch(r"[0-9a-v]{20}", spec.get("agent_id", "")): + raise ValueError("consumer Agent identity mismatch") + source = MODULE / "agents" / "main" + resources = sorted(source.rglob("*.json")) + if len(resources) != RESOURCE_COUNT: + raise ValueError(f"expected exactly {RESOURCE_COUNT} Module resources, found {len(resources)}") + planned = [(p, consumer / "agents" / owner_alias / p.relative_to(source)) for p in resources] + for src, dst in planned: + if dst.exists() and digest(dst) != digest(src): + raise ValueError(f"refusing divergent resource: {dst} (expected sha256: {digest(src)})") + return planned + + +def surface_draft(consumer: Path, owner_alias: str = "admin") -> dict: + """Surface entries for the Module, with `required_role` carried explicitly (never left to a naming convention). + + The role lives in the published Application surface, which the platform checks at admission and the broker + revalidates; the Workflow code cannot see the caller's roles. Only the Workflows listed in service-gates.json + get a role; the others (read) carry none. Review the draft, merge it into the surface, then publish it. + """ + spec = json.loads((consumer / "agents" / owner_alias / "agent-spec.json").read_text(encoding="utf-8")) + gates = json.loads(GATES.read_text(encoding="utf-8"))["workflows"] + manifest = json.loads((MODULE / "module.yaml").read_text(encoding="utf-8")) + refs = manifest["provides"]["actions"] + manifest["provides"]["queries"] + workflows = [] + for ref in refs: + entry = {"agent_id": spec["agent_id"], "workflow_id": ref["workflow_id"], "version": ref["workflow_version"]} + if ref["workflow_id"] in gates: + entry["required_role"] = gates[ref["workflow_id"]] + workflows.append(entry) + if set(gates) - {w["workflow_id"] for w in workflows}: + raise ValueError("service-gates.json names a Workflow the Module does not provide") + miniapps = [{"agent_id": spec["agent_id"], "miniapp_id": a["miniapp_id"], "version": a["miniapp_version"]} for a in manifest["provides"]["apps"]] + return {"public_surface": {"workflows": workflows, "miniapps": miniapps}} + + +def apply(consumer: Path, owner_alias: str = "admin"): + """Copy the resources and write the surface draft; a differing existing file is a conflict, nothing is overwritten.""" + planned = compose(consumer, owner_alias) + draft = json.dumps(surface_draft(consumer, owner_alias), indent=2) + "\n" + target = consumer / DRAFT_DIR / DRAFT_NAME + if target.exists() and target.read_text(encoding="utf-8") != draft: + raise ValueError(f"refusing divergent surface draft: {target}") + for src, dst in planned: + if not dst.exists(): + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(src, dst) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(draft, encoding="utf-8") + return planned, target + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--consumer-dir", required=True, type=Path) + p.add_argument("--owner-alias", default="admin") + p.add_argument("--write", action="store_true") + a = p.parse_args() + consumer = a.consumer_dir.resolve() + planned = compose(consumer, a.owner_alias) + for src, dst in planned: + print(("WRITE " if a.write else "PLAN ") + f"{src} -> {dst} [{'new' if not dst.exists() else 'identical'}]") + print(("WRITE " if a.write else "PLAN ") + f"surface draft -> {consumer / DRAFT_DIR / DRAFT_NAME} (required_role on save)") + if a.write: + apply(consumer, a.owner_alias) + print("No runtime mutation; no account creation, sharing, signing, deploy or publish. Merge the surface draft into the Application surface and publish it yourself.") + + +if __name__ == "__main__": + main() diff --git a/tooling/profile/contract/PIN.json b/tooling/profile/contract/PIN.json new file mode 100644 index 0000000..89b9c1c --- /dev/null +++ b/tooling/profile/contract/PIN.json @@ -0,0 +1,10 @@ +{ + "contract": "agentmaurice.template/v1", + "source_path": "contracts/template/v1", + "source_commit": "807c6cc87d8e16a44d783943c6241361be3f70a0", + "note": "Frozen copy, byte for byte. The sha256 values are authoritative: if the source commit is rewritten on merge, keep the hashes and update source_commit. Refresh with a new commit only through a reviewed change.", + "files": { + "namespaces.schema.json": "d084d4bfeb46416e97b2604e684b39145835d4a8216c07367a7721f9c3671324", + "tokens.schema.json": "ead27a0ad3690ee2977c2f9c41a31ca8d2d234a0809796682f44e067d9f4dd82" + } +} diff --git a/tooling/profile/contract/namespaces.schema.json b/tooling/profile/contract/namespaces.schema.json new file mode 100644 index 0000000..eb99d9a --- /dev/null +++ b/tooling/profile/contract/namespaces.schema.json @@ -0,0 +1,91 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://contracts.agentmaurice.app/template/v1/namespaces.schema.json", + "title": "AgentMaurice template v1 - contexte d'execution", + "description": "Contexte d'execution d'un gabarit : {data, company, brand, doc, i18n}. Les quatre espaces company, brand, doc et i18n sont reserves : injectes par la plateforme, jamais redefinis par un gabarit.", + "type": "object", + "required": ["data", "company", "brand", "doc", "i18n"], + "properties": { + "data": { "type": "object", "description": "Donnees metier, validees contre le input_schema du gabarit." }, + "company": { "$ref": "#/$defs/company" }, + "brand": { "$ref": "tokens.schema.json" }, + "doc": { "$ref": "#/$defs/doc" }, + "i18n": { "$ref": "#/$defs/i18n" } + }, + "additionalProperties": true, + "$defs": { + "address": { + "type": "object", + "required": ["line1", "postal_code", "city", "country"], + "properties": { + "line1": { "type": "string" }, + "line2": { "type": "string" }, + "postal_code": { "type": "string" }, + "city": { "type": "string" }, + "country": { "type": "string" } + }, + "additionalProperties": true + }, + "bank": { + "type": "object", + "description": "Coordonnees bancaires facultatives de l'entreprise (AGENT-1575). Motifs simples, sans espaces, en majuscules : ils ne portent aucune validation de cle de controle ni de format legal.", + "properties": { + "account_holder": { "type": "string" }, + "iban": { "type": "string", "minLength": 15, "maxLength": 34, "pattern": "^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$", "not": { "pattern": "\\n" } }, + "bic": { "type": "string", "pattern": "^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}([A-Z0-9]{3})?$", "not": { "pattern": "\\n" } }, + "bank_name": { "type": "string" } + }, + "additionalProperties": true + }, + "company": { + "type": "object", + "description": "Fiche entreprise (AGENT-1575).", + "required": ["legal_name"], + "properties": { + "legal_name": { "type": "string", "minLength": 1 }, + "trade_name": { "type": "string" }, + "legal_form": { "type": "string" }, + "share_capital": { "type": "string" }, + "siren": { "type": "string" }, + "siret": { "type": "string" }, + "vat_number": { "type": "string" }, + "rcs": { "type": "string" }, + "address": { "$ref": "#/$defs/address" }, + "email": { "type": "string" }, + "phone": { "type": "string" }, + "website": { "type": "string" }, + "legal_mentions": { "type": "string" }, + "bank": { "$ref": "#/$defs/bank" }, + "logo": { + "type": "object", + "required": ["ref"], + "properties": { "ref": { "type": "string", "minLength": 1 } }, + "additionalProperties": true + } + }, + "additionalProperties": true + }, + "doc": { + "type": "object", + "required": ["number", "title", "date", "version", "status", "locale"], + "properties": { + "number": { "type": "string" }, + "title": { "type": "string" }, + "date": { "type": "string", "format": "date" }, + "version": { "type": "string" }, + "status": { "enum": ["draft", "approved", "issued", "cancelled"] }, + "locale": { "type": "string" } + }, + "additionalProperties": true + }, + "i18n": { + "type": "object", + "required": ["locale", "strings"], + "properties": { + "locale": { "type": "string" }, + "strings": { "type": "object", "additionalProperties": { "type": "string" } } + }, + "additionalProperties": true + } + } +} diff --git a/tooling/profile/contract/tokens.schema.json b/tooling/profile/contract/tokens.schema.json new file mode 100644 index 0000000..98045fa --- /dev/null +++ b/tooling/profile/contract/tokens.schema.json @@ -0,0 +1,80 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://contracts.agentmaurice.app/template/v1/tokens.schema.json", + "title": "AgentMaurice template v1 - tokens de charte", + "description": "Charte graphique en jetons, consommee par tous les genres de gabarits. Exposee sous l'espace reserve `brand`.", + "type": "object", + "required": ["colors", "fonts", "logo", "page"], + "properties": { + "colors": { + "type": "object", + "required": ["primary", "secondary", "accent", "text", "muted", "background"], + "properties": { + "primary": { "$ref": "#/$defs/hex_color" }, + "secondary": { "$ref": "#/$defs/hex_color" }, + "accent": { "$ref": "#/$defs/hex_color" }, + "text": { "$ref": "#/$defs/hex_color" }, + "muted": { "$ref": "#/$defs/hex_color" }, + "background": { "$ref": "#/$defs/hex_color" } + }, + "additionalProperties": true + }, + "fonts": { + "type": "object", + "required": ["heading", "body", "mono"], + "properties": { + "heading": { "$ref": "#/$defs/font" }, + "body": { "$ref": "#/$defs/font" }, + "mono": { "$ref": "#/$defs/font" } + }, + "additionalProperties": true + }, + "logo": { + "type": "object", + "required": ["ref", "alt"], + "properties": { + "ref": { + "type": "string", + "minLength": 1, + "description": "Chemin relatif ou reference `storage://`. La plateforme la resout avant le rendu." + }, + "alt": { "type": "string", "minLength": 1 } + }, + "additionalProperties": true + }, + "page": { + "type": "object", + "required": ["size", "margins_mm"], + "properties": { + "size": { "enum": ["A4", "Letter"] }, + "margins_mm": { + "type": "object", + "required": ["top", "right", "bottom", "left"], + "properties": { + "top": { "type": "number", "minimum": 0 }, + "right": { "type": "number", "minimum": 0 }, + "bottom": { "type": "number", "minimum": 0 }, + "left": { "type": "number", "minimum": 0 } + }, + "additionalProperties": true + } + }, + "additionalProperties": true + }, + "spacing": { + "type": "object", + "description": "Optionnel : echelle d'espacement en millimetres.", + "additionalProperties": { "type": "number", "minimum": 0 } + } + }, + "additionalProperties": true, + "$defs": { + "hex_color": { "type": "string", "pattern": "^#[0-9a-fA-F]{6}$" }, + "font": { + "type": "object", + "required": ["family"], + "properties": { "family": { "type": "string", "minLength": 1 } }, + "additionalProperties": true + } + } +} diff --git a/tooling/profile/service-gates.json b/tooling/profile/service-gates.json new file mode 100644 index 0000000..560fc8f --- /dev/null +++ b/tooling/profile/service-gates.json @@ -0,0 +1,5 @@ +{ + "workflows": { + "cib-admin-profile-save": "cib_admin" + } +} diff --git a/tooling/profile/tests/fixtures/profile-body-minimal.json b/tooling/profile/tests/fixtures/profile-body-minimal.json new file mode 100644 index 0000000..302f53d --- /dev/null +++ b/tooling/profile/tests/fixtures/profile-body-minimal.json @@ -0,0 +1,21 @@ +{ + "schema_version": 1, + "company": { "legal_name": "Atelier Minimal" }, + "brand": { + "colors": { + "primary": "#112233", + "secondary": "#223344", + "accent": "#334455", + "text": "#000000", + "muted": "#777777", + "background": "#FFFFFF" + }, + "fonts": { + "heading": { "family": "Libertinus Serif" }, + "body": { "family": "Libertinus Serif" }, + "mono": { "family": "DejaVu Sans Mono" } + }, + "logo": { "ref": "storage://company-profile/logo.svg", "alt": "Logo" }, + "page": { "size": "Letter", "margins_mm": { "top": 20, "right": 20, "bottom": 20, "left": 20 } } + } +} diff --git a/tooling/profile/tests/fixtures/profile-body.json b/tooling/profile/tests/fixtures/profile-body.json new file mode 100644 index 0000000..00ee62e --- /dev/null +++ b/tooling/profile/tests/fixtures/profile-body.json @@ -0,0 +1,47 @@ +{ + "schema_version": 1, + "company": { + "legal_name": "Atelier Exemple SAS", + "trade_name": "Atelier Exemple", + "legal_form": "SAS", + "share_capital": "10 000 EUR", + "siren": "000 000 000", + "siret": "000 000 000 00000", + "vat_number": "FR00000000000", + "rcs": "RCS Exemple-sur-Seine 000 000 000", + "address": { + "line1": "1 rue de l'Exemple", + "line2": "Bâtiment A", + "postal_code": "00000", + "city": "Exemple-sur-Seine", + "country": "France" + }, + "email": "contact@atelier-exemple.invalid", + "phone": "+33 0 00 00 00 00", + "website": "https://atelier-exemple.invalid", + "legal_mentions": "Atelier Exemple SAS, capital de 10 000 EUR. Société fictive : aucune donnée réelle.", + "bank": { + "account_holder": "Atelier Exemple SAS", + "iban": "FR7600000000000000000000000", + "bic": "EXMPFRPP", + "bank_name": "Banque Exemple" + } + }, + "brand": { + "colors": { + "primary": "#1F3A5F", + "secondary": "#4F6D8F", + "accent": "#E07A1F", + "text": "#1B1B1F", + "muted": "#6B7280", + "background": "#F5F7FA" + }, + "fonts": { + "heading": { "family": "Libertinus Serif" }, + "body": { "family": "Libertinus Serif" }, + "mono": { "family": "DejaVu Sans Mono" } + }, + "logo": { "ref": "storage://company-profile/logo.svg", "alt": "Logo Atelier Exemple" }, + "page": { "size": "A4", "margins_mm": { "top": 22, "right": 20, "bottom": 22, "left": 20 } } + } +} diff --git a/tooling/profile/tests/jsonschema_subset.py b/tooling/profile/tests/jsonschema_subset.py new file mode 100644 index 0000000..8999de1 --- /dev/null +++ b/tooling/profile/tests/jsonschema_subset.py @@ -0,0 +1,81 @@ +"""Minimal JSON Schema (2020-12 subset) validator, so the offline tests need no extra package. + +It supports exactly the keywords the pinned template/v1 schemas use and raises on any other keyword, +so a schema change that the subset cannot judge fails loudly instead of being skipped. +""" +import re +from urllib.parse import urljoin + +ANNOTATIONS = {"$schema", "$id", "title", "description", "$defs", "format"} +KEYWORDS = {"$ref", "type", "enum", "required", "properties", "additionalProperties", "items", "pattern", + "minLength", "maxLength", "minimum", "not"} +TYPES = {"object": dict, "array": list, "string": str, "boolean": bool} + + +class Registry: + def __init__(self, *documents): + self.by_id = {doc["$id"]: doc for doc in documents} + + +def _type_ok(kind, value): + if kind == "number": + return isinstance(value, (int, float)) and not isinstance(value, bool) + if kind == "integer": + return isinstance(value, int) and not isinstance(value, bool) + if kind == "string" or kind == "object" or kind == "array": + return isinstance(value, TYPES[kind]) + if kind == "boolean": + return isinstance(value, bool) + raise ValueError(f"unsupported type {kind}") + + +def _resolve(ref, doc, registry): + base, _, fragment = ref.partition("#") + target = registry.by_id[urljoin(doc["$id"], base)] if base else doc + node = target + for part in [p for p in fragment.split("/") if p]: + node = node[part.replace("~1", "/").replace("~0", "~")] + return node, target + + +def validate(schema, instance, registry, doc=None, path=""): + doc = doc or schema + errors = [] + unknown = set(schema) - KEYWORDS - ANNOTATIONS + if unknown: + raise ValueError(f"unsupported schema keyword(s) {sorted(unknown)} at {path or '(root)'}") + if "$ref" in schema: + node, target = _resolve(schema["$ref"], doc, registry) + errors += validate(node, instance, registry, target, path) + if "not" in schema and not validate(schema["not"], instance, registry, doc, path): + errors.append(f"{path}: matches a forbidden schema") + kind = schema.get("type") + if kind and not _type_ok(kind, instance): + return errors + [f"{path or '(root)'}: expected {kind}"] + if "enum" in schema and instance not in schema["enum"]: + errors.append(f"{path}: not in enum") + if isinstance(instance, str): + if "minLength" in schema and len(instance) < schema["minLength"]: + errors.append(f"{path}: too short") + if "maxLength" in schema and len(instance) > schema["maxLength"]: + errors.append(f"{path}: too long") + if "pattern" in schema and not re.search(schema["pattern"], instance): + errors.append(f"{path}: pattern mismatch") + if isinstance(instance, (int, float)) and not isinstance(instance, bool) and "minimum" in schema and instance < schema["minimum"]: + errors.append(f"{path}: below minimum") + if isinstance(instance, dict): + for name in schema.get("required", []): + if name not in instance: + errors.append(f"{path}/{name}: required") + props = schema.get("properties", {}) + for name, value in instance.items(): + if name in props: + errors += validate(props[name], value, registry, doc, f"{path}/{name}") + elif schema.get("additionalProperties") is False: + errors.append(f"{path}/{name}: additional property") + elif isinstance(schema.get("additionalProperties"), dict): + errors += validate(schema["additionalProperties"], value, registry, doc, f"{path}/{name}") + if isinstance(instance, list) and "items" in schema: + for index, value in enumerate(instance): + errors += validate(schema["items"], value, registry, doc, f"{path}/{index}") + return errors diff --git a/tooling/profile/tests/test_module.py b/tooling/profile/tests/test_module.py new file mode 100644 index 0000000..bf0a0d0 --- /dev/null +++ b/tooling/profile/tests/test_module.py @@ -0,0 +1,411 @@ +"""Offline checks of the profile Module: contract pin, projection, validation, role gate, composition. + +Everything runs on synthetic fixtures. The Workflow code is executed under Node with a mocked broker; no One, +no model and no network are involved, and the real broker is not wired yet, so none of this proves runtime behaviour. +""" +import hashlib +import importlib.util +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +TESTS = Path(__file__).resolve().parent +ROOT = TESTS.parents[2] +MODULE = ROOT / "profile" +TOOLING = ROOT / "tooling/profile" +sys.path.insert(0, str(TESTS)) +from jsonschema_subset import Registry, validate # noqa: E402 + + +def load(path): + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def module_from(path, name): + spec = importlib.util.spec_from_file_location(name, path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +build = module_from(TOOLING / "build.py", "profile_build") +compose = module_from(TOOLING / "compose.py", "profile_compose") +service_roles = module_from(ROOT / "tooling/enterprise-admin/service_roles.py", "admin_service_roles") + +NAMESPACES = load(TOOLING / "contract/namespaces.schema.json") +TOKENS = load(TOOLING / "contract/tokens.schema.json") +REGISTRY = Registry(NAMESPACES, TOKENS) +BODY = load(TESTS / "fixtures/profile-body.json") +MINIMAL = load(TESTS / "fixtures/profile-body-minimal.json") +READ = load(MODULE / "agents/main/workflows/cib-profile-read.json") +SAVE = load(MODULE / "agents/main/workflows/cib-admin-profile-save.json") +CONSOLE = load(MODULE / "agents/main/miniapps/cib-profile-console.json") + +HARNESS = r''' +const [, , codePath, inputJson, scenarioJson] = process.argv; +const fs = require("fs"); +const scenario = JSON.parse(scenarioJson); +const calls = []; +async function callTool(name, args) { + calls.push({name, args}); + if (scenario.throw) { const e = typeof scenario.throw === "string" ? new Error(scenario.throw) : Object.assign(new Error(scenario.throw.message), scenario.throw); throw e; } + if (scenario.mode === "echo-save") { + return {data: {record: {namespace: args.namespace, key: args.record_key, revision: args.expected_revision + 1, owner_user_id: "user-1", permissions: {can_read: true, can_write: true, can_manage: true}, shares: [], data: scenario.stored || args.data}}}; + } + return scenario.response; +} +let code = fs.readFileSync(codePath, "utf8").replace("import { callTool } from './tools/nats_bridge.ts';", "").replace("const input = {{ json . }};", "const input = JSON.parse(process.argv[3]);"); +const main = new Function("callTool", "process", "return (async () => {" + code + "})();"); +main(callTool, process).then((result) => { console.log(JSON.stringify({calls, result})); }).catch((error) => { console.log(JSON.stringify({calls, error: String(error.message)})); }); +''' + + +def run_workflow(workflow, input_value, scenario): + code = workflow["actions"][0]["code"] + with tempfile.TemporaryDirectory() as tmp: + code_path, harness = Path(tmp) / "code.js", Path(tmp) / "harness.js" + code_path.write_text(code, encoding="utf-8") + harness.write_text(HARNESS, encoding="utf-8") + proc = subprocess.run(["node", str(harness), str(code_path), json.dumps(input_value), json.dumps(scenario)], capture_output=True, text=True) + if proc.returncode != 0: + raise AssertionError(proc.stderr) + return json.loads(proc.stdout) + + +def record(data, revision=3): + return {"data": {"record": {"namespace": "cib-profile", "key": "company-profile", "revision": revision, "owner_user_id": "user-1", "permissions": {"can_read": True, "can_write": True, "can_manage": False}, "shares": [], "data": data}}} + + +def read(data, revision=3): + return run_workflow(READ, {}, {"response": record(data, revision)}) + + +def contract_errors(profile): + errors = validate(NAMESPACES["$defs"]["company"], profile["company"], REGISTRY, NAMESPACES) + return errors + validate(TOKENS, profile["brand"], REGISTRY) + + +def fields_input(body=BODY, **overrides): + fields = run_workflow(READ, {}, {"response": record(body)})["result"]["fields"] + return {**fields, "expected_revision": "3", "confirmation_manuelle": "true", **overrides} + + +class ContractPinTest(unittest.TestCase): + def test_frozen_copy_matches_its_pin(self): + pin = load(TOOLING / "contract/PIN.json") + self.assertRegex(pin["source_commit"], r"^[0-9a-f]{40}$") + self.assertEqual(sorted(pin["files"]), ["namespaces.schema.json", "tokens.schema.json"]) + for name, expected in pin["files"].items(): + self.assertEqual(hashlib.sha256((TOOLING / "contract" / name).read_bytes()).hexdigest(), expected, name) + + def test_frozen_copy_carries_the_bank_field(self): + bank = NAMESPACES["$defs"]["bank"] + self.assertEqual(sorted(bank["properties"]), ["account_holder", "bank_name", "bic", "iban"]) + self.assertEqual(NAMESPACES["$defs"]["company"]["properties"]["bank"], {"$ref": "#/$defs/bank"}) + self.assertNotIn("bank", NAMESPACES["$defs"]["company"].get("required", [])) + + def test_subset_validator_rejects_contract_violations(self): + bad = json.loads(json.dumps(BODY)) + for key, value in (("iban", "fr7600000000000000000000000"), ("iban", "FR76 0000"), ("iban", "FR7600000000"), ("bic", "exmp"), ("account_holder", 3), ("iban", "FR7600000000000000000000000\n"), ("bic", "EXMPFRPP\n")): + bad["company"]["bank"][key] = value + self.assertTrue(contract_errors({"company": bad["company"], "brand": bad["brand"]}), (key, value)) + bad["company"]["bank"] = dict(BODY["company"]["bank"]) + worse = json.loads(json.dumps(BODY)) + worse["brand"]["colors"]["primary"] = "blue" + self.assertTrue(contract_errors(worse)) + del worse["company"]["legal_name"] + self.assertTrue(contract_errors(worse)) + + def test_fixtures_are_valid_context(self): + for body in (BODY, MINIMAL): + self.assertEqual(contract_errors({"company": body["company"], "brand": body["brand"]}), []) + + +class ManifestTest(unittest.TestCase): + def test_manifest_contract(self): + manifest = load(MODULE / "module.yaml") + self.assertEqual((manifest["key"], manifest["version"], manifest["schema_version"]), ("cib-profile", "0.1.0", 2)) + self.assertEqual([x["key"] for x in manifest["provides"]["queries"]], ["read"]) + self.assertEqual([x["key"] for x in manifest["provides"]["actions"]], ["save"]) + self.assertEqual(len(manifest["provides"]["apps"]), 1) + + def test_generator_reproduces_the_published_files(self): + published = {p: p.read_bytes() for p in MODULE.rglob("*") if p.is_file()} + build.build() + self.assertEqual(published, {p: p.read_bytes() for p in MODULE.rglob("*") if p.is_file()}) + + def test_only_the_native_broker_and_no_identity_or_legal_format(self): + for workflow in (READ, SAVE): + action = workflow["actions"][0] + self.assertEqual(action["context"], {"allowed_tools": ["recipe--application_data_v1"]}) + self.assertEqual(action["code"].count('callTool("recipe--application_data_v1"'), 1) + for forbidden in ("organization_id", "application_id", "caller_id", "owner_user_id:input", "admin_recovery", "create_account"): + self.assertNotIn(forbidden, action["code"]) + raw = " ".join(p.read_text(encoding="utf-8").lower() for p in MODULE.rglob("*.json")) + for legal in ("factur-x", "facturx", "peppol", "ubl"): + self.assertNotIn(legal, raw) + + def test_go_template_actions_are_only_the_input_binding(self): + self.assertEqual(SAVE["actions"][0]["code"].count("{{"), 1) + self.assertIn("const input = {{ json . }};", SAVE["actions"][0]["code"]) + self.assertNotIn("{{", READ["actions"][0]["code"]) + + def test_save_is_cib_admin_only_and_read_is_not_gated(self): + surface = {"workflows": [{"workflow_id": "cib-admin-profile-save", "agent_id": "a"}, {"workflow_id": "cib-profile-read", "agent_id": "a"}]} + gated = service_roles.prepare(surface, {"agents": [{"agent_id": "a", "agent_alias": "admin"}]})["public_surface"]["workflows"] + self.assertEqual({w["workflow_id"]: w.get("required_role") for w in gated}, {"cib-admin-profile-save": "cib_admin", "cib-profile-read": None}) + + def test_console_events_target_existing_workflows_and_cover_every_field(self): + form = {f["name"] for f in SAVE["forms"][0]["fields"]} + events = {e["event_id"]: e for e in CONSOLE["events"]} + self.assertEqual(events["read"]["workflow"]["workflow_id"], "cib-profile-read") + self.assertEqual(events["save"]["workflow"]["workflow_id"], "cib-admin-profile-save") + self.assertEqual(set(events["save"]["workflow"]["input"]), form) + self.assertTrue(form <= set(CONSOLE["state_schema"]["properties"]) and form <= set(CONSOLE["initial_state"])) + self.assertEqual(CONSOLE["initial_state"]["confirmation_manuelle"], "false") + for name in ("legal_name", "bank_iban", "bank_bic", "color_primary", "color_background", "logo_ref", "logo_alt"): + self.assertIn(name, form) + self.assertNotIn("upload", json.dumps(CONSOLE).lower().replace("uploading a logo is not available", "")) + + +class ReadTest(unittest.TestCase): + def test_projection_is_the_body_plus_the_derived_logo(self): + out = read(BODY) + self.assertNotIn("error", out) + result = out["result"] + profile = result["profile"] + self.assertEqual(contract_errors(profile), []) + self.assertEqual(profile["brand"], BODY["brand"]) + self.assertEqual({k: v for k, v in profile["company"].items() if k != "logo"}, BODY["company"]) + self.assertEqual(profile["company"]["logo"], {"ref": BODY["brand"]["logo"]["ref"]}) + self.assertEqual((result["found"], result["revision"], result["body"]), (True, 3, BODY)) + self.assertEqual(out["calls"], [{"name": "recipe--application_data_v1", "args": {"operation": "read", "namespace": "cib-profile", "record_key": "company-profile"}}]) + + def test_minimal_profile_has_no_bank_and_still_validates(self): + profile = read(MINIMAL)["result"]["profile"] + self.assertNotIn("bank", profile["company"]) + self.assertEqual(contract_errors(profile), []) + + def test_logo_is_single_source(self): + stored = json.loads(json.dumps(BODY)) + stored["company"]["logo"] = {"ref": "storage://other/logo.svg"} + self.assertEqual(read(stored)["error"], "company_logo_derived_from_brand") + + def test_stored_body_is_revalidated(self): + for mutate, error in ( + (lambda b: b["company"]["bank"].update(iban="FR76"), "iban_invalid"), + (lambda b: b["company"]["bank"].update(iban="FR7600000000000000000000000\n"), "stored_body_not_canonical"), + (lambda b: b["brand"]["colors"].update(primary="red"), "color_primary_invalid"), + (lambda b: b["brand"]["logo"].update(ref="logo.svg"), "logo_ref_invalid"), + (lambda b: b.update(schema_version=2), "body_schema_invalid"), + (lambda b: b["company"].update(extra="x"), "company_unknown_field"), + ): + stored = json.loads(json.dumps(BODY)) + mutate(stored) + self.assertEqual(read(stored)["error"], error) + + def test_broker_shape_errors(self): + wrong = record(BODY) + wrong["data"]["record"]["namespace"] = "cib-cases" + self.assertEqual(run_workflow(READ, {}, {"response": wrong})["error"], "broker_record_identity_invalid") + wrong = record(BODY) + wrong["data"]["record"]["permissions"] = {} + self.assertEqual(run_workflow(READ, {}, {"response": wrong})["error"], "broker_permissions_invalid") + + def test_only_the_explicit_not_found_code_means_no_profile_yet(self): + for scenario in ({"throw": {"code": "NOT_FOUND", "message": "application data record not found"}}, {"response": {"error": {"code": "NOT_FOUND"}}}): + result = run_workflow(READ, {}, scenario)["result"] + self.assertEqual((result["found"], result["revision"], result["profile"]), (False, 0, None)) + self.assertEqual(result["effects"][0]["payload"]["prefill"]["expected_revision"], "0") + + def test_every_other_broker_outcome_is_an_explicit_error(self): + cases = ( + ({"throw": {"code": "PERMISSION_DENIED", "message": "permission_denied"}}, "permission_denied"), + ({"throw": {"message": "record_not_found"}}, "record_not_found"), + ({"throw": {"message": "boom"}}, "boom"), + ({"throw": {"code": "NOT_FOUND_OTHER", "message": "application not found"}}, "application not found"), + ({"response": {"error": {"code": "PERMISSION_DENIED"}}}, "broker_error_permission_denied"), + ({"response": {"error": {}}}, "broker_error_unknown"), + ({"response": {}}, "broker_record_identity_invalid"), + ({"response": {"data": {}}}, "broker_record_identity_invalid"), + ({"response": {"data": {"record": None}}}, "broker_record_identity_invalid"), + ({"response": None}, "broker_record_identity_invalid"), + ({"response": "ok"}, "broker_record_identity_invalid"), + ) + for scenario, error in cases: + out = run_workflow(READ, {}, scenario) + self.assertNotIn("result", out, scenario) + self.assertEqual(out["error"], error, scenario) + + def test_save_never_reports_a_missing_record_as_success(self): + for scenario, error in (({"throw": {"code": "NOT_FOUND", "message": "gone"}}, "gone"), ({"response": {}}, "broker_record_identity_invalid"), + ({"response": {"error": {"code": "PERMISSION_DENIED"}}}, "broker_error_permission_denied")): + out = run_workflow(SAVE, fields_input(), scenario) + self.assertEqual((out.get("error"), "result" in out), (error, False), scenario) + + def test_projection_is_the_body_up_to_the_logo_derivation(self): + for body in (BODY, MINIMAL): + profile = read(body)["result"]["profile"] + expected_company = json.loads(json.dumps(body["company"])) + expected_company["logo"] = {"ref": body["brand"]["logo"]["ref"]} + self.assertEqual(profile, {"company": expected_company, "brand": body["brand"]}) + self.assertEqual(read(MINIMAL)["result"]["profile"]["company"], {"legal_name": "Atelier Minimal", "logo": {"ref": "storage://company-profile/logo.svg"}}) + + def test_a_stored_body_is_projected_as_is_or_refused(self): + for mutate in (lambda b: b["company"].update(trade_name=""), lambda b: b["company"].update(legal_name=" Atelier "), lambda b: b["company"]["bank"].update(iban="fr7600000000000000000000000"), + lambda b: b["brand"]["fonts"]["body"].update(family="Libertinus Serif "), lambda b: b["company"].update(address={})): + stored = json.loads(json.dumps(BODY)) + mutate(stored) + self.assertEqual(read(stored)["error"], "stored_body_not_canonical") + + def test_color_preview_has_contrast(self): + preview = {row["token"]: row for row in read(BODY)["result"]["color_preview"]} + self.assertEqual(list(preview), ["primary", "secondary", "accent", "text", "muted", "background"]) + self.assertEqual(preview["background"]["contrast_on_background"], 1) + self.assertGreater(preview["text"]["contrast_on_background"], 15) + + +class SaveTest(unittest.TestCase): + def save(self, **overrides): + return run_workflow(SAVE, fields_input(**overrides), {"mode": "echo-save"}) + + def test_round_trip_saves_the_exact_body_with_expected_revision(self): + out = self.save() + self.assertNotIn("error", out) + (call,) = out["calls"] + self.assertEqual(call["args"], {"operation": "save", "namespace": "cib-profile", "record_key": "company-profile", "data": BODY, "expected_revision": 3}) + self.assertEqual(out["result"]["revision"], 4) + self.assertEqual(contract_errors(out["result"]["profile"]), []) + + def test_minimal_round_trip(self): + out = run_workflow(SAVE, fields_input(MINIMAL), {"mode": "echo-save"}) + self.assertEqual(out["calls"][0]["args"]["data"], MINIMAL) + + def test_creation_with_revision_zero(self): + self.assertEqual(self.save(expected_revision="0")["calls"][0]["args"]["expected_revision"], 0) + + def test_manual_confirmation_and_revision_are_required(self): + for override, error in (({"confirmation_manuelle": "false"}, "manual_confirmation_required"), ({"confirmation_manuelle": "oui"}, "manual_confirmation_required"), + ({"confirmation_manuelle": ""}, "manual_confirmation_required"), ({"expected_revision": ""}, "expected_revision_required"), + ({"expected_revision": "-1"}, "expected_revision_invalid"), ({"expected_revision": "x"}, "expected_revision_invalid")): + out = self.save(**override) + self.assertEqual((out["error"], out["calls"]), (error, []), override) + + def test_iban_and_bic_are_normalised_then_checked(self): + out = self.save(bank_iban="fr76 0000 0000 0000 0000 0000 000", bank_bic="exmp frpp") + self.assertEqual(out["calls"][0]["args"]["data"]["company"]["bank"]["iban"], "FR7600000000000000000000000") + self.assertEqual(out["calls"][0]["args"]["data"]["company"]["bank"]["bic"], "EXMPFRPP") + for override, error in (({"bank_iban": "FR76"}, "iban_invalid"), ({"bank_iban": "FR76" + "0" * 31}, "iban_invalid"), ({"bank_iban": "1R7600000000000000000000000"}, "iban_invalid"), + ({"bank_bic": "EXMP-FR"}, "bic_invalid")): + out = self.save(**override) + self.assertEqual((out["error"], out["calls"]), (error, []), override) + + def test_bank_is_optional(self): + out = self.save(bank_iban="", bank_bic="", bank_account_holder="", bank_name="") + self.assertNotIn("bank", out["calls"][0]["args"]["data"]["company"]) + + def test_field_validation_refuses_before_any_broker_call(self): + for override, error in (({"legal_name": ""}, "legal_name_required"), ({"color_primary": "blue"}, "color_primary_invalid"), ({"color_background": ""}, "color_background_invalid"), + ({"logo_ref": "logo.svg"}, "logo_ref_invalid"), ({"logo_ref": "storage://a/../b.svg"}, "logo_ref_invalid"), ({"logo_ref": "https://example.invalid/logo.svg"}, "logo_ref_invalid"), + ({"logo_alt": ""}, "logo_alt_required"), ({"page_size": "A3"}, "page_size_invalid"), ({"margin_top": "-1"}, "margin_top_invalid"), + ({"margin_left": "abc"}, "margin_left_invalid"), ({"address_city": ""}, "address_city_required"), ({"font_body": ""}, "font_body_required")): + out = self.save(**override) + self.assertEqual((out["error"], out["calls"]), (error, []), override) + + def test_logo_is_set_only_through_brand(self): + out = run_workflow(SAVE, {**fields_input(), "company_logo": "storage://x/y.svg"}, {"mode": "echo-save"}) + self.assertNotIn("logo", out["calls"][0]["args"]["data"]["company"]) + + def test_forged_identity_fields_are_ignored(self): + out = run_workflow(SAVE, {**fields_input(), "owner_user_id": "forged", "organization_id": "forged", "admin_recovery": True}, {"mode": "echo-save"}) + self.assertEqual(set(out["calls"][0]["args"]), {"operation", "namespace", "record_key", "data", "expected_revision"}) + + def test_a_conflict_from_the_broker_is_not_swallowed(self): + out = run_workflow(SAVE, fields_input(), {"throw": "revision_conflict"}) + self.assertEqual(out["error"], "revision_conflict") + + def test_stored_response_is_revalidated(self): + stored = json.loads(json.dumps(BODY)) + stored["brand"]["colors"]["accent"] = "oops" + out = run_workflow(SAVE, fields_input(), {"mode": "echo-save", "stored": stored}) + self.assertEqual(out["error"], "color_accent_invalid") + + +class ComposeTest(unittest.TestCase): + def consumer(self, directory): + consumer = Path(directory) + spec = consumer / "agents/admin/agent-spec.json" + spec.parent.mkdir(parents=True) + spec.write_text(json.dumps({"schema_version": 2, "agent_alias": "admin", "agent_id": "abcdefghijklmnopqrst"})) + return consumer + + def test_plan_for_a_clean_consumer(self): + with tempfile.TemporaryDirectory() as directory: + planned = compose.compose(self.consumer(directory), "admin") + self.assertEqual(len(planned), 3) + + def test_rejects_traversal_alias_bad_identity_and_divergence(self): + with tempfile.TemporaryDirectory() as directory: + consumer = self.consumer(directory) + with self.assertRaises(ValueError): + compose.compose(consumer, "../outside") + target = consumer / "agents/admin/workflows/cib-profile-read.json" + target.parent.mkdir(parents=True) + target.write_text("{}") + with self.assertRaises(ValueError): + compose.compose(consumer, "admin") + target.write_bytes((MODULE / "agents/main/workflows/cib-profile-read.json").read_bytes()) + self.assertEqual(len(compose.compose(consumer, "admin")), 3) + with tempfile.TemporaryDirectory() as directory: + consumer = Path(directory) + spec = consumer / "agents/admin/agent-spec.json" + spec.parent.mkdir(parents=True) + spec.write_text(json.dumps({"schema_version": 2, "agent_alias": "other", "agent_id": "abcdefghijklmnopqrst"})) + with self.assertRaises(ValueError): + compose.compose(consumer, "admin") + + def test_composed_surface_declares_cib_admin_on_save_and_not_on_read(self): + with tempfile.TemporaryDirectory() as directory: + consumer = self.consumer(directory) + subprocess.run([sys.executable, str(TOOLING / "compose.py"), "--consumer-dir", str(consumer), "--owner-alias", "admin", "--write"], check=True, capture_output=True) + draft = load(consumer / "surface-drafts/cib-profile.surface-draft.json")["public_surface"] + workflows = {w["workflow_id"]: w for w in draft["workflows"]} + self.assertEqual(workflows["cib-admin-profile-save"]["required_role"], "cib_admin") + self.assertNotIn("required_role", workflows["cib-profile-read"]) + self.assertEqual({w["agent_id"] for w in draft["workflows"]}, {"abcdefghijklmnopqrst"}) + self.assertEqual([m["miniapp_id"] for m in draft["miniapps"]], ["cib-profile-console"]) + self.assertTrue((consumer / "agents/admin/workflows/cib-admin-profile-save.json").is_file()) + # idempotent, and a divergent draft is refused + compose.apply(consumer, "admin") + (consumer / "surface-drafts/cib-profile.surface-draft.json").write_text("{}\n") + with self.assertRaises(ValueError): + compose.apply(consumer, "admin") + + def test_plan_mode_writes_nothing(self): + with tempfile.TemporaryDirectory() as directory: + consumer = self.consumer(directory) + proc = subprocess.run([sys.executable, str(TOOLING / "compose.py"), "--consumer-dir", str(consumer)], check=True, capture_output=True, text=True) + self.assertIn("required_role on save", proc.stdout) + self.assertFalse((consumer / "surface-drafts").exists()) + + def test_the_gate_file_names_only_provided_workflows_and_only_save(self): + gates = load(TOOLING / "service-gates.json")["workflows"] + self.assertEqual(gates, {"cib-admin-profile-save": "cib_admin"}) + + def test_workflow_code_cannot_see_roles_and_ignores_a_forged_one(self): + # The role is enforced by the platform on the published surface and revalidated by the broker; the code gets + # no caller identity. A non-admin call is refused before the code runs, which a mocked broker cannot show; + # here we only prove the code never trusts a role sent in its input. + code = SAVE["actions"][0]["code"] + self.assertNotIn("cib_admin", code) + out = run_workflow(SAVE, {**fields_input(), "role": "cib_admin", "roles": ["cib_admin"], "required_role": "cib_admin"}, {"mode": "echo-save"}) + self.assertEqual(set(out["calls"][0]["args"]), {"operation", "namespace", "record_key", "data", "expected_revision"}) + refused = run_workflow(SAVE, fields_input(), {"throw": {"code": "PERMISSION_DENIED", "message": "required_role_missing"}}) + self.assertEqual((refused["error"], "result" in refused), ("required_role_missing", False)) + + +if __name__ == "__main__": + unittest.main()