Review a LinkedIn Business Manager v2 handoff adversarially. Use only closed v2 fields. Notes are informational and cannot change state, coverage, role scope, verification or freshness. Never invent an ID, owner, role, approval, receipt, timestamp or result. Validate the source, then recompute all derived fields with the executable engine. Return the computed state, reason and a prioritized action list from the structured findings. Do not stop at a generic evaluator next action when a finding identifies a more specific missing fact. For an unknown asset owner, name the asset and ask for the verified owner organization ID plus a current ownership receipt. trust_root is this local contract's evidence bootstrap, not a LinkedIn role: set it true only for one independently confirmed PERSON whose self identity receipt and organization identity receipt satisfy the executable contract; keep it false for every other identity and never enable it merely to make a record pass. Reject placeholder or unregistered identities, mismatched ownership, role/task/template/evidence bindings, prohibited capabilities, broader access without a structured approved exception, stale/future/impossible/reversed dates, missing approvals, denied or sign-in-only checks, forged derived fields and weak dependency coverage. JSON SCHEMA ```json {"type":"object","additionalProperties":false,"required":["schema_version","contract_version","record_id","revision","fictional","review","identities","organization","assignee","assets","evidence","external_requests","notes"],"properties":{"schema_version":{"const":"maestro.linkedin-business-manager.record.v2"},"contract_version":{"const":"2.0.0"},"record_id":{"type":["string","null"]},"revision":{"type":"integer","minimum":1},"fictional":{"type":"boolean"},"review":{"type":"object","additionalProperties":false,"required":["reviewed_at","max_evidence_age_days"],"properties":{"reviewed_at":{"type":"string","format":"date-time","pattern":"Z$"},"max_evidence_age_days":{"type":"integer","minimum":0}}},"identities":{"type":"array","minItems":1,"items":{"type":"object","additionalProperties":false,"required":["identity_id","name","type","organization_id","authorized_approver","verification_evidence_id","trust_root"],"properties":{"identity_id":{"type":"string","pattern":"^(person|org|bm):[a-z0-9][a-z0-9.-]{2,}$"},"name":{"type":"string","minLength":1},"type":{"enum":["PERSON","ORGANIZATION","BUSINESS_MANAGER"]},"organization_id":{"type":"string","minLength":1},"authorized_approver":{"type":"boolean"},"verification_evidence_id":{"type":"string","minLength":1},"trust_root":{"type":"boolean"}}}},"organization":{"type":"object","additionalProperties":false,"required":["name","business_manager_name","business_manager_id","controlling_organization_id","ownership_evidence_id","ownership_event_at"],"properties":{"name":{"type":"string","minLength":1},"business_manager_name":{"type":"string","minLength":1},"business_manager_id":{"type":"string","minLength":1},"controlling_organization_id":{"type":"string","minLength":1},"ownership_evidence_id":{"type":["string","null"]},"ownership_event_at":{"type":["string","null"]}}},"assignee":{"type":"object","additionalProperties":false,"required":["assignee_id","name","type","organization_id","separate_organization","linkedin_profile_ref","partner_business_manager_id","business_manager_role","invitation_status","invitation_evidence_id","invitation_event_at","admin_exception","notes"],"properties":{"assignee_id":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"type":{"enum":["PERSON","PARTNER"]},"organization_id":{"type":"string","minLength":1},"separate_organization":{"type":"boolean"},"linkedin_profile_ref":{"type":["string","null"]},"partner_business_manager_id":{"type":["string","null"]},"business_manager_role":{"enum":["ADMIN","EMPLOYEE","CONTRACTOR",null]},"invitation_status":{"enum":["NOT_REQUIRED","NOT_SENT","PENDING","ACCEPTED","DECLINED","UNKNOWN"]},"invitation_evidence_id":{"type":["string","null"]},"invitation_event_at":{"type":["string","null"]},"admin_exception":{"type":"object","additionalProperties":false,"required":["reason_code","decision","reviewer_id","decided_at","expires_at","evidence_id"],"properties":{"reason_code":{"type":["string","null"]},"decision":{"type":["string","null"]},"reviewer_id":{"type":["string","null"]},"decided_at":{"type":["string","null"]},"expires_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"notes":{"type":"array","items":{"type":"string"}}}},"assets":{"type":"array","minItems":1,"items":{"type":"object","additionalProperties":false,"required":["asset_id","required","type","name","native_id","relationship","owner_organization_id","ownership_evidence_id","ownership_event_at","task_code","required_capabilities","prohibited_capabilities","requested_role","scope_decision","role_exception","request","approval","verification","notes"],"properties":{"asset_id":{"type":"string","minLength":1},"required":{"type":"boolean"},"type":{"enum":["AD_ACCOUNT","PAGE"]},"name":{"type":"string","minLength":1},"native_id":{"type":"string","minLength":1},"relationship":{"enum":["OWNED","SHARED"]},"owner_organization_id":{"type":"string","minLength":1},"ownership_evidence_id":{"type":["string","null"]},"ownership_event_at":{"type":["string","null"]},"task_code":{"enum":["REPORTING","CAMPAIGN_EDITING","CREATIVE_EDITING","BILLING","ACCOUNT_ADMINISTRATION","SPONSOR_CONTENT","LEAD_FORM_DOWNLOAD","LANDING_PAGE_EDIT","PAGE_CONTENT","PAGE_ANALYTICS","PAGE_ADMINISTRATION"]},"required_capabilities":{"type":"array","minItems":1,"maxItems":1,"uniqueItems":true,"items":{"enum":["REPORTING","CAMPAIGN_EDITING","CREATIVE_EDITING","BILLING","ACCOUNT_ADMINISTRATION","SPONSOR_CONTENT","LEAD_FORM_DOWNLOAD","LANDING_PAGE_EDIT","PAGE_CONTENT","PAGE_ANALYTICS","PAGE_ADMINISTRATION"]}},"prohibited_capabilities":{"type":"array","uniqueItems":true,"items":{"enum":["REPORTING","CAMPAIGN_EDITING","CREATIVE_EDITING","BILLING","ACCOUNT_ADMINISTRATION","SPONSOR_CONTENT","LEAD_FORM_DOWNLOAD","LANDING_PAGE_EDIT","PAGE_CONTENT","PAGE_ANALYTICS","PAGE_ADMINISTRATION"]}},"requested_role":{"type":"string","minLength":1},"scope_decision":{"enum":["EXACT","BROADER_APPROVED","BROADER_REJECTED","UNKNOWN"]},"role_exception":{"type":"object","additionalProperties":false,"required":["reason_code","decision","reviewer_id","decided_at","expires_at","evidence_id"],"properties":{"reason_code":{"type":["string","null"]},"decision":{"type":["string","null"]},"reviewer_id":{"type":["string","null"]},"decided_at":{"type":["string","null"]},"expires_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"request":{"type":"object","additionalProperties":false,"required":["status","requester_id","approver_id","event_at","evidence_id"],"properties":{"status":{"enum":["NOT_SUBMITTED","SUBMITTED","UNKNOWN"]},"requester_id":{"type":["string","null"]},"approver_id":{"type":["string","null"]},"event_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"approval":{"type":"object","additionalProperties":false,"required":["decision","approver_id","approved_role","event_at","evidence_id"],"properties":{"decision":{"enum":["APPROVED","REJECTED","PENDING","UNKNOWN"]},"approver_id":{"type":["string","null"]},"approved_role":{"type":["string","null"]},"event_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"verification":{"type":"object","additionalProperties":false,"required":["assignee_id","task_code","task_template_id","outcome","observations_valid","event_at","evidence_id"],"properties":{"assignee_id":{"type":["string","null"]},"task_code":{"type":["string","null"]},"task_template_id":{"type":["string","null"]},"outcome":{"enum":["SUCCEEDED","DENIED","ERROR","PENDING","NOT_RUN","UNKNOWN"]},"observations_valid":{"type":"boolean"},"event_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"notes":{"type":"array","items":{"type":"string"}}}}},"evidence":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["evidence_id","kind","subject_type","subject_id","actor_id","event_at","captured_at","reference","owner_id","capability","task_template_id","asserted_owner_organization_id","recipient_organization_id"],"properties":{"evidence_id":{"type":"string","minLength":1},"kind":{"enum":["IDENTITY_VERIFICATION","BUSINESS_MANAGER_OWNERSHIP","ASSET_OWNERSHIP","PERSON_INVITATION","ACCESS_REQUEST","ACCESS_APPROVAL","ROLE_EXCEPTION","NATIVE_TASK","SHARED_ASSET"]},"subject_type":{"enum":["IDENTITY","BUSINESS_MANAGER","ASSET","ASSIGNEE"]},"subject_id":{"type":"string","minLength":1},"actor_id":{"type":["string","null"]},"event_at":{"type":"string","format":"date-time","pattern":"Z$"},"captured_at":{"type":"string","format":"date-time","pattern":"Z$"},"reference":{"type":"string","pattern":"^((https://)|(urn:)|(fictional://receipt/))"},"owner_id":{"type":"string","minLength":1},"capability":{"enum":["REPORTING","CAMPAIGN_EDITING","CREATIVE_EDITING","BILLING","ACCOUNT_ADMINISTRATION","SPONSOR_CONTENT","LEAD_FORM_DOWNLOAD","LANDING_PAGE_EDIT","PAGE_CONTENT","PAGE_ANALYTICS","PAGE_ADMINISTRATION",null]},"task_template_id":{"type":["string","null"]},"asserted_owner_organization_id":{"type":["string","null"]},"recipient_organization_id":{"type":["string","null"]}}}},"external_requests":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["request_id","status","blocking","global_blocker","owner_id","next_action","blocked_nodes"],"properties":{"request_id":{"type":"string","minLength":1},"status":{"enum":["OPEN","RESOLVED","NOT_APPLICABLE"]},"blocking":{"type":"boolean"},"global_blocker":{"type":"boolean"},"owner_id":{"type":"string","minLength":1},"next_action":{"type":"string","minLength":1},"blocked_nodes":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["asset_id","node"],"properties":{"asset_id":{"type":"string","minLength":1},"node":{"enum":["OWNERSHIP","ROLE","REQUEST","APPROVAL","VERIFICATION"]}}}}}}},"notes":{"type":"array","items":{"type":"string"}}},"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://maestrogtm.com/schemas/linkedin-business-manager-record-v2.json"} ``` EXECUTABLE ENGINE ```javascript /* Closed-field v2 contract. Freeform notes never affect decisions. */ export const CONTRACT_VERSION = "2.0.0"; export const SCHEMA_VERSION = "maestro.linkedin-business-manager.record.v2"; export const STATES = ["REPAIR_REQUIRED", "READY_TO_REQUEST", "VERIFY_ACCESS", "HANDOFF_COMPLETE"]; export const SOURCE_SCHEMA_JSON = String.raw`{"type":"object","additionalProperties":false,"required":["schema_version","contract_version","record_id","revision","fictional","review","identities","organization","assignee","assets","evidence","external_requests","notes"],"properties":{"schema_version":{"const":"maestro.linkedin-business-manager.record.v2"},"contract_version":{"const":"2.0.0"},"record_id":{"type":["string","null"]},"revision":{"type":"integer","minimum":1},"fictional":{"type":"boolean"},"review":{"type":"object","additionalProperties":false,"required":["reviewed_at","max_evidence_age_days"],"properties":{"reviewed_at":{"type":"string","format":"date-time","pattern":"Z$"},"max_evidence_age_days":{"type":"integer","minimum":0}}},"identities":{"type":"array","minItems":1,"items":{"type":"object","additionalProperties":false,"required":["identity_id","name","type","organization_id","authorized_approver","verification_evidence_id","trust_root"],"properties":{"identity_id":{"type":"string","pattern":"^(person|org|bm):[a-z0-9][a-z0-9.-]{2,}$"},"name":{"type":"string","minLength":1},"type":{"enum":["PERSON","ORGANIZATION","BUSINESS_MANAGER"]},"organization_id":{"type":"string","minLength":1},"authorized_approver":{"type":"boolean"},"verification_evidence_id":{"type":"string","minLength":1},"trust_root":{"type":"boolean"}}}},"organization":{"type":"object","additionalProperties":false,"required":["name","business_manager_name","business_manager_id","controlling_organization_id","ownership_evidence_id","ownership_event_at"],"properties":{"name":{"type":"string","minLength":1},"business_manager_name":{"type":"string","minLength":1},"business_manager_id":{"type":"string","minLength":1},"controlling_organization_id":{"type":"string","minLength":1},"ownership_evidence_id":{"type":["string","null"]},"ownership_event_at":{"type":["string","null"]}}},"assignee":{"type":"object","additionalProperties":false,"required":["assignee_id","name","type","organization_id","separate_organization","linkedin_profile_ref","partner_business_manager_id","business_manager_role","invitation_status","invitation_evidence_id","invitation_event_at","admin_exception","notes"],"properties":{"assignee_id":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"type":{"enum":["PERSON","PARTNER"]},"organization_id":{"type":"string","minLength":1},"separate_organization":{"type":"boolean"},"linkedin_profile_ref":{"type":["string","null"]},"partner_business_manager_id":{"type":["string","null"]},"business_manager_role":{"enum":["ADMIN","EMPLOYEE","CONTRACTOR",null]},"invitation_status":{"enum":["NOT_REQUIRED","NOT_SENT","PENDING","ACCEPTED","DECLINED","UNKNOWN"]},"invitation_evidence_id":{"type":["string","null"]},"invitation_event_at":{"type":["string","null"]},"admin_exception":{"type":"object","additionalProperties":false,"required":["reason_code","decision","reviewer_id","decided_at","expires_at","evidence_id"],"properties":{"reason_code":{"type":["string","null"]},"decision":{"type":["string","null"]},"reviewer_id":{"type":["string","null"]},"decided_at":{"type":["string","null"]},"expires_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"notes":{"type":"array","items":{"type":"string"}}}},"assets":{"type":"array","minItems":1,"items":{"type":"object","additionalProperties":false,"required":["asset_id","required","type","name","native_id","relationship","owner_organization_id","ownership_evidence_id","ownership_event_at","task_code","required_capabilities","prohibited_capabilities","requested_role","scope_decision","role_exception","request","approval","verification","notes"],"properties":{"asset_id":{"type":"string","minLength":1},"required":{"type":"boolean"},"type":{"enum":["AD_ACCOUNT","PAGE"]},"name":{"type":"string","minLength":1},"native_id":{"type":"string","minLength":1},"relationship":{"enum":["OWNED","SHARED"]},"owner_organization_id":{"type":"string","minLength":1},"ownership_evidence_id":{"type":["string","null"]},"ownership_event_at":{"type":["string","null"]},"task_code":{"enum":["REPORTING","CAMPAIGN_EDITING","CREATIVE_EDITING","BILLING","ACCOUNT_ADMINISTRATION","SPONSOR_CONTENT","LEAD_FORM_DOWNLOAD","LANDING_PAGE_EDIT","PAGE_CONTENT","PAGE_ANALYTICS","PAGE_ADMINISTRATION"]},"required_capabilities":{"type":"array","minItems":1,"maxItems":1,"uniqueItems":true,"items":{"enum":["REPORTING","CAMPAIGN_EDITING","CREATIVE_EDITING","BILLING","ACCOUNT_ADMINISTRATION","SPONSOR_CONTENT","LEAD_FORM_DOWNLOAD","LANDING_PAGE_EDIT","PAGE_CONTENT","PAGE_ANALYTICS","PAGE_ADMINISTRATION"]}},"prohibited_capabilities":{"type":"array","uniqueItems":true,"items":{"enum":["REPORTING","CAMPAIGN_EDITING","CREATIVE_EDITING","BILLING","ACCOUNT_ADMINISTRATION","SPONSOR_CONTENT","LEAD_FORM_DOWNLOAD","LANDING_PAGE_EDIT","PAGE_CONTENT","PAGE_ANALYTICS","PAGE_ADMINISTRATION"]}},"requested_role":{"type":"string","minLength":1},"scope_decision":{"enum":["EXACT","BROADER_APPROVED","BROADER_REJECTED","UNKNOWN"]},"role_exception":{"type":"object","additionalProperties":false,"required":["reason_code","decision","reviewer_id","decided_at","expires_at","evidence_id"],"properties":{"reason_code":{"type":["string","null"]},"decision":{"type":["string","null"]},"reviewer_id":{"type":["string","null"]},"decided_at":{"type":["string","null"]},"expires_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"request":{"type":"object","additionalProperties":false,"required":["status","requester_id","approver_id","event_at","evidence_id"],"properties":{"status":{"enum":["NOT_SUBMITTED","SUBMITTED","UNKNOWN"]},"requester_id":{"type":["string","null"]},"approver_id":{"type":["string","null"]},"event_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"approval":{"type":"object","additionalProperties":false,"required":["decision","approver_id","approved_role","event_at","evidence_id"],"properties":{"decision":{"enum":["APPROVED","REJECTED","PENDING","UNKNOWN"]},"approver_id":{"type":["string","null"]},"approved_role":{"type":["string","null"]},"event_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"verification":{"type":"object","additionalProperties":false,"required":["assignee_id","task_code","task_template_id","outcome","observations_valid","event_at","evidence_id"],"properties":{"assignee_id":{"type":["string","null"]},"task_code":{"type":["string","null"]},"task_template_id":{"type":["string","null"]},"outcome":{"enum":["SUCCEEDED","DENIED","ERROR","PENDING","NOT_RUN","UNKNOWN"]},"observations_valid":{"type":"boolean"},"event_at":{"type":["string","null"]},"evidence_id":{"type":["string","null"]}}},"notes":{"type":"array","items":{"type":"string"}}}}},"evidence":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["evidence_id","kind","subject_type","subject_id","actor_id","event_at","captured_at","reference","owner_id","capability","task_template_id","asserted_owner_organization_id","recipient_organization_id"],"properties":{"evidence_id":{"type":"string","minLength":1},"kind":{"enum":["IDENTITY_VERIFICATION","BUSINESS_MANAGER_OWNERSHIP","ASSET_OWNERSHIP","PERSON_INVITATION","ACCESS_REQUEST","ACCESS_APPROVAL","ROLE_EXCEPTION","NATIVE_TASK","SHARED_ASSET"]},"subject_type":{"enum":["IDENTITY","BUSINESS_MANAGER","ASSET","ASSIGNEE"]},"subject_id":{"type":"string","minLength":1},"actor_id":{"type":["string","null"]},"event_at":{"type":"string","format":"date-time","pattern":"Z$"},"captured_at":{"type":"string","format":"date-time","pattern":"Z$"},"reference":{"type":"string","pattern":"^((https://)|(urn:)|(fictional://receipt/))"},"owner_id":{"type":"string","minLength":1},"capability":{"enum":["REPORTING","CAMPAIGN_EDITING","CREATIVE_EDITING","BILLING","ACCOUNT_ADMINISTRATION","SPONSOR_CONTENT","LEAD_FORM_DOWNLOAD","LANDING_PAGE_EDIT","PAGE_CONTENT","PAGE_ANALYTICS","PAGE_ADMINISTRATION",null]},"task_template_id":{"type":["string","null"]},"asserted_owner_organization_id":{"type":["string","null"]},"recipient_organization_id":{"type":["string","null"]}}}},"external_requests":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["request_id","status","blocking","global_blocker","owner_id","next_action","blocked_nodes"],"properties":{"request_id":{"type":"string","minLength":1},"status":{"enum":["OPEN","RESOLVED","NOT_APPLICABLE"]},"blocking":{"type":"boolean"},"global_blocker":{"type":"boolean"},"owner_id":{"type":"string","minLength":1},"next_action":{"type":"string","minLength":1},"blocked_nodes":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["asset_id","node"],"properties":{"asset_id":{"type":"string","minLength":1},"node":{"enum":["OWNERSHIP","ROLE","REQUEST","APPROVAL","VERIFICATION"]}}}}}}},"notes":{"type":"array","items":{"type":"string"}}},"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://maestrogtm.com/schemas/linkedin-business-manager-record-v2.json"}`; export const SOURCE_SCHEMA = JSON.parse(SOURCE_SCHEMA_JSON); export const ROLE_CATALOG = { AD_ACCOUNT: { VIEWER: ["REPORTING"], CREATIVE_MANAGER: ["REPORTING", "CREATIVE_EDITING"], CAMPAIGN_MANAGER: ["REPORTING", "CREATIVE_EDITING", "CAMPAIGN_EDITING"], ACCOUNT_MANAGER: ["REPORTING", "CREATIVE_EDITING", "CAMPAIGN_EDITING", "ACCOUNT_ADMINISTRATION"], BILLING_ADMIN: ["REPORTING", "CREATIVE_EDITING", "CAMPAIGN_EDITING", "ACCOUNT_ADMINISTRATION", "BILLING"], }, PAGE: { ANALYST: ["PAGE_ANALYTICS"], SPONSORED_CONTENT_POSTER: ["SPONSOR_CONTENT"], LEAD_GEN_FORMS_MANAGER: ["LEAD_FORM_DOWNLOAD"], LANDING_PAGES_MANAGER: ["LANDING_PAGE_EDIT"], CONTENT_ADMIN: ["PAGE_ANALYTICS", "SPONSOR_CONTENT", "PAGE_CONTENT"], SUPER_ADMIN: ["PAGE_ANALYTICS", "SPONSOR_CONTENT", "LEAD_FORM_DOWNLOAD", "LANDING_PAGE_EDIT", "PAGE_CONTENT", "PAGE_ADMINISTRATION"], }, }; export const EXACT_ROLES = { AD_ACCOUNT: {REPORTING:"VIEWER",CAMPAIGN_EDITING:"CAMPAIGN_MANAGER",CREATIVE_EDITING:"CREATIVE_MANAGER",BILLING:"BILLING_ADMIN",ACCOUNT_ADMINISTRATION:"ACCOUNT_MANAGER"}, PAGE: {SPONSOR_CONTENT:"SPONSORED_CONTENT_POSTER",LEAD_FORM_DOWNLOAD:"LEAD_GEN_FORMS_MANAGER",LANDING_PAGE_EDIT:"LANDING_PAGES_MANAGER",PAGE_CONTENT:"CONTENT_ADMIN",PAGE_ANALYTICS:"ANALYST",PAGE_ADMINISTRATION:"SUPER_ADMIN"}, }; export const TASK_CATALOG = { REPORTING:"OPEN_NAMED_REPORT_V1",CAMPAIGN_EDITING:"OPEN_NAMED_CAMPAIGN_EDITOR_NO_PUBLISH_V1",CREATIVE_EDITING:"OPEN_NAMED_CREATIVE_EDITOR_NO_PUBLISH_V1", BILLING:"OPEN_BILLING_CONTROL_NO_CHANGE_V1",ACCOUNT_ADMINISTRATION:"OPEN_ACCOUNT_ACCESS_CONTROL_NO_CHANGE_V1",SPONSOR_CONTENT:"SELECT_PAGE_IN_SPONSORSHIP_PICKER_NO_PUBLISH_V1", LEAD_FORM_DOWNLOAD:"OPEN_NAMED_FORM_DOWNLOAD_CONTROL_NO_DOWNLOAD_V1",LANDING_PAGE_EDIT:"OPEN_NAMED_LANDING_PAGE_EDITOR_NO_PUBLISH_V1",PAGE_CONTENT:"OPEN_PAGE_CONTENT_CONTROL_NO_PUBLISH_V1", PAGE_ANALYTICS:"OPEN_NAMED_PAGE_REPORT_V1",PAGE_ADMINISTRATION:"OPEN_PAGE_ADMIN_CONTROL_NO_CHANGE_V1", }; const text=value=>typeof value==="string"&&value.trim().length>0; const badId=value=>!text(value)||/(^|[\s_-])(unknown|unassigned|not[\s_-]+supplied|not[\s_-]+provided|n\/?a|none|null|tbd|todo|placeholder)([\s_-]|$)/i.test(value.trim()); const stableIdentityId=value=>typeof value==="string"&&/^(person|org|bm):[a-z0-9][a-z0-9.-]{2,}$/.test(value); const referenceOk=(value,fictional=null)=>{if(typeof value!=="string"||/(^|[/:._-])(todo|tbd|placeholder|unknown|unassigned|not[._-]?provided|not[._-]?supplied)([/:._-]|$)/i.test(value))return false;if(value.startsWith("fictional://receipt/"))return(fictional===null||fictional===true)&&/^fictional:\/\/receipt\/[a-z0-9][a-z0-9._-]{2,}$/i.test(value);if(fictional===true)return false;if(value.startsWith("https://")){try{const u=new URL(value);return!!u.hostname&&u.hostname.includes(".")&&!/^(example\.(com|org|net)|localhost|invalid)$/i.test(u.hostname)&&u.pathname!=="/";}catch{return false;}}if(value.startsWith("urn:"))return/^urn:[a-z0-9][a-z0-9-]{1,}:[a-z0-9][a-z0-9:._-]{2,}$/i.test(value);return false;}; const iso=value=>{if(typeof value!=="string")return false;const m=value.match(/^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):([0-5]\d):([0-5]\d)(?:\.(\d+))?Z$/);if(!m)return false;const[,y,mo,d]=m,dt=new Date(Date.UTC(+y,+mo-1,+d));return dt.getUTCFullYear()===+y&&dt.getUTCMonth()+1===+mo&&dt.getUTCDate()===+d;}; const clone=value=>JSON.parse(JSON.stringify(value)); const finding=(code,field,reason,next_action,owner_id=null)=>({code,field,reason,next_action,owner_id}); const humanLabel=value=>String(value||"required").toLowerCase().replaceAll("_"," ").replace(/\b\w/g,c=>c.toUpperCase()); const exactKeys=(value,allowed,required=allowed)=>{if(!value||typeof value!=="object"||Array.isArray(value))return false;const keys=Object.keys(value);return keys.every(k=>allowed.includes(k))&&required.every(k=>keys.includes(k));}; const sortJson=v=>Array.isArray(v)?v.map(sortJson):v&&typeof v==="object"?Object.fromEntries(Object.keys(v).sort().map(k=>[k,sortJson(v[k])])):v; function validateSchemaValue(value,schema,path="",errors=[]){ const types=Array.isArray(schema.type)?schema.type:schema.type?[schema.type]:[]; const isType=t=>t==="null"?value===null:t==="array"?Array.isArray(value):t==="object"?!!value&&typeof value==="object"&&!Array.isArray(value):t==="integer"?Number.isInteger(value):t==="number"?typeof value==="number"&&Number.isFinite(value):t==="string"?typeof value==="string":t==="boolean"?typeof value==="boolean":false; if(types.length&&!types.some(isType)){errors.push(`${path||"/"}:type`);return errors;} if(Object.hasOwn(schema,"const")&&JSON.stringify(value)!==JSON.stringify(schema.const))errors.push(`${path||"/"}:const`); if(schema.enum&&!schema.enum.some(x=>JSON.stringify(sortJson(x))===JSON.stringify(sortJson(value))))errors.push(`${path||"/"}:enum`); if(typeof value==="string"){ if(schema.minLength!==undefined&&Array.from(value).lengthschema.maximum)errors.push(`${path}:maximum`); } if(Array.isArray(value)){ if(schema.minItems!==undefined&&value.lengthschema.maxItems)errors.push(`${path}:maxItems`); if(schema.uniqueItems){const seen=new Set();for(const item of value){const key=JSON.stringify(sortJson(item));if(seen.has(key)){errors.push(`${path}:uniqueItems`);break;}seen.add(key);}} if(schema.items)for(let i=0;itypeof x==="string"))throw new Error("Source fails the closed v2 shape"); if(!exactKeys(r.review,["reviewed_at","max_evidence_age_days"])||!iso(r.review.reviewed_at)||!Number.isInteger(r.review.max_evidence_age_days)||r.review.max_evidence_age_days<0)throw new Error("Review policy fails the closed v2 shape"); const identityKeys=["identity_id","name","type","organization_id","authorized_approver","verification_evidence_id","trust_root"];for(const x of r.identities)if(!exactKeys(x,identityKeys)||typeof x.authorized_approver!=="boolean"||typeof x.trust_root!=="boolean"||!["PERSON","ORGANIZATION","BUSINESS_MANAGER"].includes(x.type)||!stableIdentityId(x.identity_id)||![x.name,x.organization_id,x.verification_evidence_id].every(text))throw new Error("Identity fails the closed v2 shape"); const nullableString=x=>x===null||typeof x==="string",exceptionKeys=["reason_code","decision","reviewer_id","decided_at","expires_at","evidence_id"],exceptionShape=x=>exactKeys(x,exceptionKeys)&&exceptionKeys.every(k=>nullableString(x[k])); const orgKeys=["name","business_manager_name","business_manager_id","controlling_organization_id","ownership_evidence_id","ownership_event_at"];if(!exactKeys(r.organization,orgKeys)||![r.organization.name,r.organization.business_manager_name,r.organization.business_manager_id,r.organization.controlling_organization_id].every(text)||!nullableString(r.organization.ownership_evidence_id)||!nullableString(r.organization.ownership_event_at))throw new Error("Organization fails the closed v2 shape"); const assigneeKeys=["assignee_id","name","type","organization_id","separate_organization","linkedin_profile_ref","partner_business_manager_id","business_manager_role","invitation_status","invitation_evidence_id","invitation_event_at","admin_exception","notes"];if(!exactKeys(r.assignee,assigneeKeys)||![r.assignee.assignee_id,r.assignee.name,r.assignee.organization_id].every(text)||!["PERSON","PARTNER"].includes(r.assignee.type)||typeof r.assignee.separate_organization!=="boolean"||!["ADMIN","EMPLOYEE","CONTRACTOR",null].includes(r.assignee.business_manager_role)||!["NOT_REQUIRED","NOT_SENT","PENDING","ACCEPTED","DECLINED","UNKNOWN"].includes(r.assignee.invitation_status)||!["linkedin_profile_ref","partner_business_manager_id","invitation_evidence_id","invitation_event_at"].every(k=>nullableString(r.assignee[k]))||!exceptionShape(r.assignee.admin_exception)||!Array.isArray(r.assignee.notes)||!r.assignee.notes.every(x=>typeof x==="string"))throw new Error("Assignee fails the closed v2 shape"); const evKeys=["evidence_id","kind","subject_type","subject_id","actor_id","event_at","captured_at","reference","owner_id","capability","task_template_id","asserted_owner_organization_id","recipient_organization_id"],kinds=["IDENTITY_VERIFICATION","BUSINESS_MANAGER_OWNERSHIP","ASSET_OWNERSHIP","PERSON_INVITATION","ACCESS_REQUEST","ACCESS_APPROVAL","ROLE_EXCEPTION","NATIVE_TASK","SHARED_ASSET"],subjectTypes=["IDENTITY","BUSINESS_MANAGER","ASSET","ASSIGNEE"],caps=Object.keys(TASK_CATALOG);for(const x of r.evidence)if(!exactKeys(x,evKeys)||![x.evidence_id,x.subject_id,x.owner_id].every(text)||!kinds.includes(x.kind)||!subjectTypes.includes(x.subject_type)||!iso(x.event_at)||!iso(x.captured_at)||!referenceOk(x.reference)||!["actor_id","task_template_id","asserted_owner_organization_id","recipient_organization_id"].every(k=>nullableString(x[k]))||!(x.capability===null||caps.includes(x.capability)))throw new Error("Evidence fails the closed v2 shape"); const requestKeys=["status","requester_id","approver_id","event_at","evidence_id"],approvalKeys=["decision","approver_id","approved_role","event_at","evidence_id"],verifyKeys=["assignee_id","task_code","task_template_id","outcome","observations_valid","event_at","evidence_id"],assetKeys=["asset_id","required","type","name","native_id","relationship","owner_organization_id","ownership_evidence_id","ownership_event_at","task_code","required_capabilities","prohibited_capabilities","requested_role","scope_decision","role_exception","request","approval","verification","notes"]; for(const x of r.assets)if(!exactKeys(x,assetKeys)||![x.asset_id,x.name,x.native_id,x.owner_organization_id,x.requested_role].every(text)||typeof x.required!=="boolean"||!["AD_ACCOUNT","PAGE"].includes(x.type)||!["OWNED","SHARED"].includes(x.relationship)||!caps.includes(x.task_code)||!Array.isArray(x.required_capabilities)||x.required_capabilities.length!==1||!x.required_capabilities.every(c=>caps.includes(c))||!Array.isArray(x.prohibited_capabilities)||!x.prohibited_capabilities.every(c=>caps.includes(c))||!Array.isArray(x.notes)||!x.notes.every(n=>typeof n==="string")||!exceptionShape(x.role_exception)||!exactKeys(x.request,requestKeys)||!["NOT_SUBMITTED","SUBMITTED","UNKNOWN"].includes(x.request.status)||!requestKeys.slice(1).every(k=>nullableString(x.request[k]))||!exactKeys(x.approval,approvalKeys)||!["APPROVED","REJECTED","PENDING","UNKNOWN"].includes(x.approval.decision)||!approvalKeys.slice(1).every(k=>nullableString(x.approval[k]))||!exactKeys(x.verification,verifyKeys)||!verifyKeys.filter(k=>k!=="observations_valid").every(k=>nullableString(x.verification[k]))||!["SUCCEEDED","DENIED","ERROR","PENDING","NOT_RUN","UNKNOWN"].includes(x.verification.outcome)||typeof x.verification.observations_valid!=="boolean")throw new Error("Asset fails the closed v2 shape"); const externalKeys=["request_id","status","blocking","global_blocker","owner_id","next_action","blocked_nodes"];for(const x of r.external_requests)if(!exactKeys(x,externalKeys)||![x.request_id,x.owner_id,x.next_action].every(text)||!["OPEN","RESOLVED","NOT_APPLICABLE"].includes(x.status)||typeof x.blocking!=="boolean"||typeof x.global_blocker!=="boolean"||!Array.isArray(x.blocked_nodes)||!x.blocked_nodes.every(n=>exactKeys(n,["asset_id","node"])&&text(n.asset_id)&&["OWNERSHIP","ROLE","REQUEST","APPROVAL","VERIFICATION"].includes(n.node)))throw new Error("External request fails the closed v2 shape"); } export function evaluate(input){ if(!input||typeof input!=="object"||Array.isArray(input))throw new Error("Source must be an object"); if(input.schema_version!==SCHEMA_VERSION||input.contract_version!==CONTRACT_VERSION)throw new Error("Unsupported contract"); assertSourceShape(input); const r=clone(input),repairs=[],requests=[],verifies=[],ids=new Set(),evidence=new Map(),identities=new Map(); const reviewAt=r.review?.reviewed_at,maxAge=r.review?.max_evidence_age_days; const dateState=value=>{if(!iso(value)||!iso(reviewAt)||!Number.isInteger(maxAge)||maxAge<0)return"INVALID";const d=Date.parse(reviewAt)-Date.parse(value);return d<0?"FUTURE":d/86400000>maxAge?"STALE":"CURRENT";}; const current=value=>dateState(value)==="CURRENT",futureExpiry=value=>iso(value)&&iso(reviewAt)&&Date.parse(value)>Date.parse(reviewAt),chronological=(...values)=>values.every(iso)&&values.every((v,i)=>!i||Date.parse(values[i-1])<=Date.parse(v)); const unique=(id,path)=>{if(badId(id)||ids.has(id)){repairs.push(finding("ID_INVALID",path,"IDs must be unique and non-placeholder.","Assign a unique stable ID."));return false;}ids.add(id);return true;}; if(!iso(reviewAt)||!Number.isInteger(maxAge)||maxAge<0)repairs.push(finding("REVIEW_POLICY_INVALID","/review","Review time or freshness policy is invalid.","Set a valid UTC review time and non-negative age limit.")); for(const[i,x]of(r.identities||[]).entries())if(unique(x.identity_id,`/identities/${i}/identity_id`)){identities.set(x.identity_id,x);if(badId(x.name)||badId(x.organization_id))repairs.push(finding("IDENTITY_INVALID",`/identities/${i}`,"Identity is incomplete or uses a placeholder.","Record the exact person or organization identity."));} for(const[i,e]of(r.evidence||[]).entries())if(unique(e.evidence_id,`/evidence/${i}/evidence_id`))evidence.set(e.evidence_id,e); const trustRootOk=x=>{if(!x||x.type!=="PERSON"||x.trust_root!==true||!stableIdentityId(x.identity_id)||badId(x.name))return false;const org=identities.get(x.organization_id),p=evidence.get(x.verification_evidence_id),op=evidence.get(org?.verification_evidence_id);return org?.type==="ORGANIZATION"&&org.organization_id===org.identity_id&&!!p&&p.kind==="IDENTITY_VERIFICATION"&&p.subject_type==="IDENTITY"&&p.subject_id===x.identity_id&&p.actor_id===x.identity_id&&p.owner_id===x.identity_id&&p.asserted_owner_organization_id===x.organization_id&&p.capability===null&&p.task_template_id===null&&p.recipient_organization_id===null&&referenceOk(p.reference,r.fictional)&¤t(p.event_at)&¤t(p.captured_at)&&chronological(p.event_at,p.captured_at,reviewAt)&&!!op&&op.kind==="IDENTITY_VERIFICATION"&&op.subject_type==="IDENTITY"&&op.subject_id===org.identity_id&&op.actor_id===x.identity_id&&op.owner_id===x.identity_id&&op.asserted_owner_organization_id===org.identity_id&&op.capability===null&&op.task_template_id===null&&op.recipient_organization_id===null&&referenceOk(op.reference,r.fictional)&¤t(op.event_at)&¤t(op.captured_at)&&chronological(op.event_at,op.captured_at,reviewAt);}; const rootProofs=x=>[evidence.get(x?.verification_evidence_id),evidence.get(identities.get(x?.organization_id)?.verification_evidence_id)].filter(Boolean); const rootPredates=(x,time)=>trustRootOk(x)&&iso(time)&&rootProofs(x).every(p=>chronological(p.event_at,time)); const rawIdentityProofOk=x=>{const proof=evidence.get(x?.verification_evidence_id),actor=identities.get(proof?.actor_id),owner=identities.get(proof?.owner_id);if(!x||!proof||proof.kind!=="IDENTITY_VERIFICATION"||proof.subject_type!=="IDENTITY"||proof.subject_id!==x.identity_id||proof.asserted_owner_organization_id!==x.organization_id||proof.capability!==null||proof.task_template_id!==null||proof.recipient_organization_id!==null||!referenceOk(proof.reference,r.fictional)||!current(proof.event_at)||!current(proof.captured_at)||!chronological(proof.event_at,proof.captured_at,reviewAt))return false;if(x.trust_root===true)return x.type==="PERSON"&&trustRootOk(x);return rootPredates(actor,proof.event_at)&&rootPredates(owner,proof.event_at);}; const identityOk=(id,type=null,authorized=false)=>{const x=identities.get(id);if(!x||badId(id)||badId(x.name)||!stableIdentityId(id)||type&&x.type!==type||authorized&&x.authorized_approver!==true)return false;const org=identities.get(x.organization_id),orgOk=x.type==="ORGANIZATION"?x.organization_id===x.identity_id:org?.type==="ORGANIZATION"&&rawIdentityProofOk(org);return orgOk&&rawIdentityProofOk(x);}; const identityEstablishedBefore=(id,time)=>{const x=identities.get(id),proof=evidence.get(x?.verification_evidence_id),org=identities.get(x?.organization_id),orgProof=evidence.get(org?.verification_evidence_id),actor=identities.get(proof?.actor_id),owner=identities.get(proof?.owner_id);if(!identityOk(id)||!iso(time))return false;if(x.trust_root===true)return rootPredates(x,time);return chronological(proof.event_at,time)&&chronological(orgProof?.event_at,time)&&rootPredates(actor,proof.event_at)&&rootPredates(owner,proof.event_at);}; for(const x of identities.values())if(!rawIdentityProofOk(x))repairs.push(finding("IDENTITY_PROOF_INVALID",`/identities/${x.identity_id}/verification_evidence_id`,"Identity proof lacks a valid trust-root actor and custodian, self-proof, organization binding, locator or current chronology.","Revalidate this identity with a valid trust-root proof and custodian.")); const evidencePartiesOk=e=>!!e&&identityEstablishedBefore(e.actor_id,e.event_at)&&identities.get(e.owner_id)?.type==="PERSON"&&identityEstablishedBefore(e.owner_id,e.event_at); const evidenceOk=(id,kind,subjectType,subjectId,actorId,eventAt,capability=null,template=null,assertedOwner=null,recipient=undefined)=>{const e=evidence.get(id);return!!e&&e.kind===kind&&e.subject_type===subjectType&&e.subject_id===subjectId&&(!actorId||e.actor_id===actorId)&&e.event_at===eventAt&&(!capability||e.capability===capability)&&(!template||e.task_template_id===template)&&(!assertedOwner||e.asserted_owner_organization_id===assertedOwner)&&(recipient===undefined||e.recipient_organization_id===recipient)&&evidencePartiesOk(e)&&referenceOk(e.reference,r.fictional)&¤t(e.event_at)&¤t(e.captured_at)&&chronological(e.event_at,e.captured_at,reviewAt);}; for(const[id,e]of evidence)if(!current(e.event_at)||!current(e.captured_at)||!chronological(e.event_at,e.captured_at,reviewAt))repairs.push(finding("EVIDENCE_DATE_INVALID","/evidence",`Evidence ${id} has an invalid, future, stale or reversed event/capture time.`,"Correct or refresh the underlying event evidence; a new capture cannot change when the event occurred.")); const org=r.organization||{}; if([org.name,org.business_manager_name,org.business_manager_id,org.controlling_organization_id].some(badId)||!identityOk(org.controlling_organization_id,"ORGANIZATION"))repairs.push(finding("ORGANIZATION_INCOMPLETE","/organization","Organization identity is incomplete.","Record exact organization and Business Manager IDs.")); const orgOwnershipProof=evidence.get(org.ownership_evidence_id),orgOwnership=identityEstablishedBefore(org.controlling_organization_id,org.ownership_event_at)&&identities.get(orgOwnershipProof?.actor_id)?.type==="PERSON"&&evidenceOk(org.ownership_evidence_id,"BUSINESS_MANAGER_OWNERSHIP","BUSINESS_MANAGER",org.business_manager_id,null,org.ownership_event_at,null,null,org.controlling_organization_id,null); if(!orgOwnership)repairs.push(finding("BUSINESS_MANAGER_OWNERSHIP_UNVERIFIED","/organization/ownership_evidence_id","Business Manager ownership is not current and bound to its native ID.","Attach current ownership evidence.",org.controlling_organization_id)); const a=r.assignee||{};let assigneeAccess=false; if([a.name,a.organization_id].some(badId)||!["PERSON","PARTNER"].includes(a.type)||!identityOk(a.organization_id,"ORGANIZATION"))repairs.push(finding("ASSIGNEE_INCOMPLETE","/assignee","Assignee identity is incomplete.","Record exact assignee identity and organization.")); if(a.type==="PARTNER"){ const valid=a.separate_organization===true&&!badId(a.partner_business_manager_id)&&a.assignee_id===a.partner_business_manager_id&&identityOk(a.organization_id,"ORGANIZATION")&&identityOk(a.assignee_id,"BUSINESS_MANAGER")&&identities.get(a.assignee_id)?.organization_id===a.organization_id&&a.organization_id!==org.controlling_organization_id; if(!valid)repairs.push(finding("PARTNER_IDENTITY_INVALID","/assignee","Partner must use its exact Business Manager ID and a separate organization.","Correct the partner identity.")); const exceptionEmpty=Object.values(a.admin_exception||{}).every(v=>v===null); if(a.business_manager_role!==null||a.invitation_status!=="NOT_REQUIRED"||a.invitation_evidence_id!==null||a.invitation_event_at!==null||a.linkedin_profile_ref!==null||!exceptionEmpty)repairs.push(finding("PARTNER_PERSON_FIELDS_CONFLICT","/assignee","Partner has person-only role, profile, invitation or exception fields.","Remove person-only fields.")); const activityTimes=(r.assets||[]).filter(x=>x.required).flatMap(x=>[x.scope_decision==="BROADER_APPROVED"?x.role_exception?.decided_at:null,x.request?.status==="SUBMITTED"?x.request.event_at:null,x.approval?.decision==="APPROVED"?x.approval.event_at:null,["SUCCEEDED","DENIED","ERROR"].includes(x.verification?.outcome)?x.verification.event_at:null]).filter(v=>v!==null&&v!==undefined),identityBeforeActivity=activityTimes.every(time=>identityEstablishedBefore(a.assignee_id,time)&&identityEstablishedBefore(a.organization_id,time)); if(valid&&!identityBeforeActivity)repairs.push(finding("PARTNER_IDENTITY_CHRONOLOGY_INVALID","/assignee","Partner Business Manager and organization proofs must predate access activity.","Verify the partner organization and Business Manager before requesting access.")); assigneeAccess=valid&&identityBeforeActivity&&a.business_manager_role===null&&a.invitation_status==="NOT_REQUIRED"&&a.invitation_evidence_id===null&&a.invitation_event_at===null&&a.linkedin_profile_ref===null&&exceptionEmpty; }else if(a.type==="PERSON"){ const identityValid=a.separate_organization===false&&!badId(a.linkedin_profile_ref)&&a.assignee_id===a.linkedin_profile_ref&&identityOk(a.organization_id,"ORGANIZATION")&&identityOk(a.assignee_id,"PERSON")&&identities.get(a.assignee_id)?.organization_id===a.organization_id&&a.partner_business_manager_id===null; if(!identityValid)repairs.push(finding("PERSON_IDENTITY_INVALID","/assignee","Person must use an exact registered profile reference and no partner ID.","Correct the person identity.")); const invitation=a.invitation_status==="ACCEPTED"&&evidenceOk(a.invitation_evidence_id,"PERSON_INVITATION","ASSIGNEE",a.assignee_id,a.assignee_id,a.invitation_event_at,null,null,a.organization_id,null); if(!invitation)repairs.push(finding("PERSON_INVITATION_UNVERIFIED","/assignee/invitation_status","Person invitation acceptance is not verified.","Accept the invitation and attach a current receipt.",a.assignee_id)); const roleValid=["EMPLOYEE","CONTRACTOR","ADMIN"].includes(a.business_manager_role);if(!roleValid)repairs.push(finding("PERSON_ROLE_INVALID","/assignee/business_manager_role","Person role is invalid.","Select the smallest allowed person role.")); let adminValid=true;if(a.business_manager_role==="ADMIN"){const j=a.admin_exception||{};adminValid=["TEMPORARY_ADMINISTRATION","OWNERSHIP_RECOVERY"].includes(j.reason_code)&&j.decision==="APPROVED"&&identityOk(j.reviewer_id,"PERSON",true)&¤t(j.decided_at)&&futureExpiry(j.expires_at)&&chronological(j.decided_at,a.invitation_event_at)&&evidenceOk(j.evidence_id,"ROLE_EXCEPTION","ASSIGNEE",a.assignee_id,j.reviewer_id,j.decided_at,null,null,a.organization_id,null);if(!adminValid)repairs.push(finding("ADMIN_EXCEPTION_INVALID","/assignee/admin_exception","Admin lacks an approved structured exception with reviewer, evidence, chronology and future expiry.","Reduce the role or attach a valid exception."));}else if(!Object.values(a.admin_exception||{}).every(v=>v===null)){adminValid=false;repairs.push(finding("ADMIN_EXCEPTION_CONFLICT","/assignee/admin_exception","A non-Admin assignee has a populated Admin exception.","Clear the Admin exception or select and approve Admin."));} assigneeAccess=identityValid&&invitation&&roleValid&&adminValid; }else repairs.push(finding("ASSIGNEE_TYPE_INVALID","/assignee/type","Assignee must be PERSON or PARTNER.","Choose the correct type.")); if(a.type==="PERSON"&&assigneeAccess){ const inviteOrder=(r.assets||[]).filter(x=>x.required).every(x=>{ const milestones=[a.business_manager_role==="ADMIN"?a.admin_exception?.decided_at:null,a.invitation_event_at,x.scope_decision==="BROADER_APPROVED"?x.role_exception?.decided_at:null,x.request?.status==="SUBMITTED"?x.request.event_at:null,x.approval?.decision==="APPROVED"?x.approval.event_at:null,["SUCCEEDED","DENIED","ERROR"].includes(x.verification?.outcome)?x.verification.event_at:null].filter(v=>v!==null&&v!==undefined); return milestones.every(iso)&&milestones.every((v,i)=>i===0||Date.parse(milestones[i-1])<=Date.parse(v)); }); if(!inviteOrder){assigneeAccess=false;repairs.push(finding("INVITATION_CHRONOLOGY_INVALID","/assignee/invitation_event_at","The accepted invitation does not precede the assignee's asset activity.","Accept the invitation before requesting or verifying asset access."));} } for(const[i,x]of(r.external_requests||[]).entries()){ unique(x.request_id,`/external_requests/${i}/request_id`);const targets=x.blocked_nodes||[],targetsValid=x.global_blocker===true?targets.length===0:targets.length>0&&targets.every(n=>(r.assets||[]).some(a=>a.asset_id===n.asset_id)); if(!["OPEN","RESOLVED","NOT_APPLICABLE"].includes(x.status)||!identityOk(x.owner_id,"PERSON")||badId(x.next_action)||!targetsValid)repairs.push(finding("EXTERNAL_REQUEST_INVALID",`/external_requests/${i}`,"External request is incomplete or has invalid targets.","Assign exact blocked nodes and resolve it or mark it not applicable."));else if(x.blocking&&x.status==="OPEN")repairs.push(finding("BLOCKING_EXTERNAL_REQUEST",`/external_requests/${i}`,"A blocking request remains open.",x.next_action,x.owner_id)); } const openBlockers=(r.external_requests||[]).filter(x=>x.blocking&&x.status==="OPEN"),globalBlocked=openBlockers.some(x=>x.global_blocker),blocked=(assetId,node)=>globalBlocked||openBlockers.some(x=>(x.blocked_nodes||[]).some(n=>n.asset_id===assetId&&n.node===node)); const required=(r.assets||[]).filter(x=>x.required);if(!required.length)repairs.push(finding("REQUIRED_ASSETS_MISSING","/assets","No required assets exist.","Add required Pages and ad accounts.")); const counts={required:required.length,ownership:0,requested:0,approved:0,verified:0},nodeStatus=[]; for(const[i,x]of(r.assets||[]).entries()){ const base=`/assets/${i}`;unique(x.asset_id,`${base}/asset_id`);if(!x.required)continue; if([x.type,x.name,x.native_id,x.owner_organization_id,x.task_code,x.requested_role].some(badId))repairs.push(finding("ASSET_INCOMPLETE",base,"Required asset fields are incomplete.","Complete the structured asset record.")); const owned=x.relationship==="OWNED",shared=x.relationship==="SHARED",ownershipKind=owned?"ASSET_OWNERSHIP":"SHARED_ASSET",ownerRelation=owned?x.owner_organization_id===org.controlling_organization_id:x.owner_organization_id!==org.controlling_organization_id&&identityEstablishedBefore(x.owner_organization_id,x.ownership_event_at)&&identities.get(x.owner_organization_id)?.type==="ORGANIZATION",ownershipProof=evidence.get(x.ownership_evidence_id),ownershipActorValid=identities.get(ownershipProof?.actor_id)?.type==="PERSON"; const ownershipMilestones=[org.ownership_event_at,x.ownership_event_at,x.scope_decision==="BROADER_APPROVED"?x.role_exception?.decided_at:null,x.request?.status==="SUBMITTED"?x.request.event_at:null,x.approval?.decision==="APPROVED"?x.approval.event_at:null,["SUCCEEDED","DENIED","ERROR"].includes(x.verification?.outcome)?x.verification.event_at:null].filter(v=>v!==null&&v!==undefined),ownershipOrder=ownershipMilestones.every(iso)&&ownershipMilestones.every((v,j)=>j===0||Date.parse(ownershipMilestones[j-1])<=Date.parse(v)); const ownership=!blocked(x.asset_id,"OWNERSHIP")&&ownershipOrder&&orgOwnership&&assigneeAccess&&ownerRelation&&ownershipActorValid&&evidenceOk(x.ownership_evidence_id,ownershipKind,"ASSET",x.native_id,null,x.ownership_event_at,null,null,x.owner_organization_id,shared?org.controlling_organization_id:null); if(!ownershipOrder)repairs.push(finding("OWNERSHIP_CHRONOLOGY_INVALID",`${base}/ownership_event_at`,"Business Manager and asset ownership must predate role, request, approval and verification activity.","Correct the ownership chronology before requesting access.")); if(!ownership)repairs.push(finding("ASSET_OWNERSHIP_UNVERIFIED",`${base}/ownership_evidence_id`,"Asset ownership or an upstream ownership prerequisite is not verified.",`Attach current ownership evidence for ${x.name||x.asset_id}.`,x.owner_organization_id));if(ownership)counts.ownership++; const requiredCaps=Array.isArray(x.required_capabilities)?x.required_capabilities:[],prohibited=new Set(x.prohibited_capabilities||[]),roleCaps=ROLE_CATALOG[x.type]?.[x.requested_role]||[],exact=EXACT_ROLES[x.type]?.[x.task_code]; const taskContract=requiredCaps.length===1&&requiredCaps[0]===x.task_code&&TASK_CATALOG[x.task_code]===x.verification?.task_template_id;if(!taskContract)repairs.push(finding("TASK_CONTRACT_INVALID",`${base}/task_code`,"Task, required capability and native-check template do not match.","Use the generated closed task contract.")); const capabilityConflict=requiredCaps.some(c=>prohibited.has(c))||roleCaps.some(c=>prohibited.has(c));if(capabilityConflict)repairs.push(finding("PROHIBITED_CAPABILITY_CONFLICT",`${base}/prohibited_capabilities`,"The requested role grants a prohibited capability.","Choose a role without the prohibited capability or revise the task boundary.")); let role=false;if(taskContract&&!capabilityConflict&&roleCaps.includes(x.task_code)){if(x.requested_role===exact){role=x.scope_decision==="EXACT"&&Object.values(x.role_exception||{}).every(v=>v===null);if(!role)repairs.push(finding("ROLE_SCOPE_CONFLICT",`${base}/scope_decision`,"Exact role has a conflicting or populated exception.","Set scope to EXACT and clear the exception."));}else{const j=x.role_exception||{};role=x.scope_decision==="BROADER_APPROVED"&&["PLATFORM_ROLE_BUNDLE","TEMPORARY_ADMINISTRATION"].includes(j.reason_code)&&j.decision==="APPROVED"&&identityOk(j.reviewer_id,"PERSON",true)&¤t(j.decided_at)&&futureExpiry(j.expires_at)&&evidenceOk(j.evidence_id,"ROLE_EXCEPTION","ASSET",x.native_id,j.reviewer_id,j.decided_at,x.task_code,null,x.owner_organization_id,shared?org.controlling_organization_id:null);if(!role)repairs.push(finding("BROADER_ROLE_UNAPPROVED",`${base}/role_exception`,`The exact role is ${exact}; the broader role lacks a valid structured exception.`,"Reduce the role or attach an approved exception."));}} if(blocked(x.asset_id,"ROLE"))role=false; if(!roleCaps.includes(x.task_code))repairs.push(finding("ROLE_TASK_MISMATCH",`${base}/requested_role`,"Role does not support the closed task.",`Use ${exact||"a supported role"}.`)); const q=x.request||{},p=x.approval||{},v=x.verification||{}; if(q.status==="SUBMITTED"&&(!identityOk(q.requester_id,"PERSON")||!identityOk(q.approver_id,"PERSON",true)||identities.get(q.requester_id)?.organization_id!==org.controlling_organization_id||identities.get(q.approver_id)?.organization_id!==org.controlling_organization_id))repairs.push(finding("REQUEST_IDENTITY_INVALID",`${base}/request`,"Submitted request uses an unknown, placeholder, unauthorized or wrong-organization identity.","Bind the request to registered requester and approver identities in the controlling organization.")); const qProof=evidence.get(q.evidence_id),pProof=evidence.get(p.evidence_id),vProof=evidence.get(v.evidence_id); if(q.status==="SUBMITTED"&&qProof&&!evidencePartiesOk(qProof))repairs.push(finding("REQUEST_RECEIPT_IDENTITY_INVALID",`${base}/request/evidence_id`,"Request receipt actor or custodian was not verified before the event.","Reissue the request with verified receipt parties.")); if(p.decision==="APPROVED"&&pProof&&!evidencePartiesOk(pProof))repairs.push(finding("APPROVAL_RECEIPT_IDENTITY_INVALID",`${base}/approval/evidence_id`,"Approval receipt actor or custodian was not verified before the event.","Reissue the approval with verified receipt parties.")); if(["SUCCEEDED","DENIED","ERROR"].includes(v.outcome)&&vProof&&!evidencePartiesOk(vProof))repairs.push(finding("VERIFICATION_RECEIPT_IDENTITY_INVALID",`${base}/verification/evidence_id`,"Native receipt actor or custodian was not verified before the event.","Repeat the native check with verified receipt parties.")); if(q.status==="SUBMITTED"&&qProof&&(!["ACCESS_REQUEST"].includes(qProof.kind)||qProof.subject_type!=="ASSET"||qProof.subject_id!==x.native_id||qProof.actor_id!==q.requester_id||qProof.asserted_owner_organization_id!==x.owner_organization_id||qProof.recipient_organization_id!==(shared?org.controlling_organization_id:null)))repairs.push(finding("REQUEST_RECEIPT_BINDING_INVALID",`${base}/request/evidence_id`,"Request receipt conflicts with the asset, actor or owner/recipient organizations.","Attach the exact request receipt for this asset and organization.")); if(p.decision==="APPROVED"&&pProof&&(!["ACCESS_APPROVAL"].includes(pProof.kind)||pProof.subject_type!=="ASSET"||pProof.subject_id!==x.native_id||pProof.actor_id!==p.approver_id||pProof.asserted_owner_organization_id!==x.owner_organization_id||pProof.recipient_organization_id!==(shared?org.controlling_organization_id:null)))repairs.push(finding("APPROVAL_RECEIPT_BINDING_INVALID",`${base}/approval/evidence_id`,"Approval receipt conflicts with the asset, actor or owner/recipient organizations.","Attach the exact approval receipt for this asset and organization.")); if(["SUCCEEDED","DENIED","ERROR"].includes(v.outcome)&&vProof&&(!["NATIVE_TASK"].includes(vProof.kind)||vProof.subject_type!=="ASSET"||vProof.subject_id!==x.native_id||vProof.actor_id!==a.assignee_id||vProof.asserted_owner_organization_id!==x.owner_organization_id||vProof.recipient_organization_id!==(shared?org.controlling_organization_id:null)))repairs.push(finding("VERIFICATION_RECEIPT_BINDING_INVALID",`${base}/verification/evidence_id`,"Native receipt conflicts with the asset, assignee or owner/recipient organizations.","Repeat the named native check and capture its exact receipt.")); if(q.status==="SUBMITTED"&&(!current(q.event_at)||evidence.get(q.evidence_id)?.event_at!==q.event_at))repairs.push(finding("REQUEST_DATE_INVALID",`${base}/request/event_at`,"Request time is invalid or does not match its receipt.","Correct the request event and bound evidence timestamp.")); if(q.status==="SUBMITTED"&&evidence.get(q.evidence_id)?.capability!==x.task_code)repairs.push(finding("REQUEST_RECEIPT_BINDING_INVALID",`${base}/request/evidence_id`,"Request receipt is bound to a different capability.","Capture the request receipt for the named capability.")); if(p.decision==="APPROVED"&&(!identityOk(p.approver_id,"PERSON",true)||p.approver_id!==q.approver_id))repairs.push(finding("APPROVAL_IDENTITY_INVALID",`${base}/approval`,"Approval uses an unknown, placeholder, unauthorized or mismatched approver.","Bind approval to the request's authorized approver.")); if(p.decision==="APPROVED"&&p.approved_role!==x.requested_role)repairs.push(finding("APPROVAL_SCOPE_CONFLICT",`${base}/approval/approved_role`,"Approval role conflicts with the requested role.","Approve the exact requested role or revise the request.")); if(p.decision==="APPROVED"&&(!current(p.event_at)||evidence.get(p.evidence_id)?.event_at!==p.event_at||!chronological(q.event_at,p.event_at)))repairs.push(finding("APPROVAL_DATE_INVALID",`${base}/approval/event_at`,"Approval time is invalid, predates the request or differs from its receipt.","Correct the approval chronology and bound evidence timestamp.")); if(p.decision==="APPROVED"&&evidence.get(p.evidence_id)?.capability!==x.task_code)repairs.push(finding("APPROVAL_RECEIPT_BINDING_INVALID",`${base}/approval/evidence_id`,"Approval receipt is bound to a different capability.","Capture the approval receipt for the named capability.")); if(!["NOT_RUN","PENDING","UNKNOWN"].includes(v.outcome)&&(!current(v.event_at)||evidence.get(v.evidence_id)?.event_at!==v.event_at||!chronological(p.event_at,v.event_at)))repairs.push(finding("VERIFICATION_DATE_INVALID",`${base}/verification/event_at`,"Verification time is invalid, predates approval or differs from its receipt.","Repeat the native check and bind its exact event timestamp.")); if(!["NOT_RUN","PENDING","UNKNOWN"].includes(v.outcome)&&(evidence.get(v.evidence_id)?.capability!==x.task_code||evidence.get(v.evidence_id)?.task_template_id!==v.task_template_id))repairs.push(finding("VERIFICATION_RECEIPT_BINDING_INVALID",`${base}/verification/evidence_id`,"Native receipt is bound to a different capability or task template.","Repeat the generated native check and capture its bound receipt.")); const j=x.role_exception||{};if(x.scope_decision==="BROADER_APPROVED"&&(![j.decided_at,q.event_at,p.event_at,v.event_at].filter(v=>v!==null&&v!==undefined).every(iso)||[j.decided_at,q.event_at,p.event_at,v.event_at].filter(v=>v!==null&&v!==undefined).some((v,i,arr)=>i>0&&Date.parse(arr[i-1])>Date.parse(v))||!futureExpiry(j.expires_at))){repairs.push(finding("ROLE_EXCEPTION_TEMPORAL_INVALID",`${base}/role_exception`,"Role exception was expired or approved after access activity began.","Approve the exception before the request and keep its expiry after review."));role=false;} const requestOk=!blocked(x.asset_id,"REQUEST")&&ownership&&role&&q.status==="SUBMITTED"&&identityOk(q.requester_id,"PERSON")&&identityOk(q.approver_id,"PERSON",true)&&identities.get(q.requester_id)?.organization_id===org.controlling_organization_id&&identities.get(q.approver_id)?.organization_id===org.controlling_organization_id&&evidenceOk(q.evidence_id,"ACCESS_REQUEST","ASSET",x.native_id,q.requester_id,q.event_at,x.task_code,null,x.owner_organization_id,shared?org.controlling_organization_id:null); const approvalOk=!blocked(x.asset_id,"APPROVAL")&&requestOk&&p.decision==="APPROVED"&&identityOk(p.approver_id,"PERSON",true)&&p.approver_id===q.approver_id&&p.approved_role===x.requested_role&&evidenceOk(p.evidence_id,"ACCESS_APPROVAL","ASSET",x.native_id,p.approver_id,p.event_at,x.task_code,null,x.owner_organization_id,shared?org.controlling_organization_id:null)&&chronological(q.event_at,p.event_at); if(requestOk)counts.requested++;if(!requestOk){const requesterName=identities.get(q.requester_id)?.name||q.requester_id||"the requester",approverName=identities.get(q.approver_id)?.name||q.approver_id||"the authorized approver",assigneeName=a.name||a.assignee_id||"the assignee";requests.push(finding("REQUEST_REQUIRED",`${base}/request`,`${x.name||x.asset_id} lacks a valid request.`,`${requesterName} sends ${approverName} a request to give ${assigneeName} the ${humanLabel(x.requested_role)} role on ${x.name||"the asset"}. Save the request date and receipt.`,identityOk(q.approver_id,"PERSON")?q.approver_id:null));}else if(p.decision==="REJECTED")repairs.push(finding("APPROVAL_REJECTED",`${base}/approval`,`${x.name||x.asset_id} access was rejected.`,"Resolve the rejection or change scope.",p.approver_id));else if(!approvalOk)requests.push(finding("APPROVAL_REQUIRED",`${base}/approval`,`${x.name||x.asset_id} lacks matching approval.`,`Have ${q.approver_id} approve or reject ${x.requested_role}.`,q.approver_id));if(approvalOk)counts.approved++; const binding=v.assignee_id===a.assignee_id&&v.task_code===x.task_code&&v.task_template_id===TASK_CATALOG[x.task_code];if(approvalOk&&!binding)repairs.push(finding("VERIFICATION_BINDING_INVALID",`${base}/verification`,`${x.name||x.asset_id} verification is bound to the wrong assignee, task or template.`,"Repeat the generated check with the named assignee.",a.assignee_id)); const verificationOk=!blocked(x.asset_id,"VERIFICATION")&&approvalOk&&binding&&v.outcome==="SUCCEEDED"&&v.observations_valid===true&&evidenceOk(v.evidence_id,"NATIVE_TASK","ASSET",x.native_id,a.assignee_id,v.event_at,x.task_code,v.task_template_id,x.owner_organization_id,shared?org.controlling_organization_id:null)&&chronological(q.event_at,p.event_at,v.event_at); if(approvalOk&&["DENIED","ERROR"].includes(v.outcome))repairs.push(finding("NATIVE_TASK_FAILED",`${base}/verification`,`${x.name||x.asset_id} native task failed.`,"Repair access and repeat the generated check.",a.assignee_id));else if(approvalOk&&!verificationOk)verifies.push(finding("NATIVE_TASK_REQUIRED",`${base}/verification`,`${x.name||x.asset_id} lacks successful native verification.`,`Have ${a.name||"the assignee"} complete ${TASK_CATALOG[x.task_code]||"the generated task"}.`,a.assignee_id));if(verificationOk)counts.verified++; nodeStatus.push({asset_id:x.asset_id,ownership,role:ownership&&role,request:requestOk,approval:approvalOk,verification:verificationOk}); } const findings=[...repairs,...requests,...verifies],state=repairs.length?"REPAIR_REQUIRED":requests.length?"READY_TO_REQUEST":verifies.length?"VERIFY_ACCESS":"HANDOFF_COMPLETE",materialFresh=orgOwnership&&assigneeAccess&&nodeStatus.every(n=>n.ownership); return{schema_version:"maestro.linkedin-business-manager.evaluation.v2",contract_version:CONTRACT_VERSION,record_id:r.record_id??null,revision:r.revision,fictional:r.fictional,state,reason:(repairs[0]||requests[0]||verifies[0])?.reason||"Every required asset has current ownership, exact scope, matching approval and successful native verification.",next_action:(repairs[0]||requests[0]||verifies[0])?.next_action||`Archive the handoff and review it after ${reviewAt}.`,asset_coverage:counts,node_status:nodeStatus,evidence_freshness:{reviewed_at:reviewAt??null,max_evidence_age_days:maxAge??null,status:materialFresh&&!repairs.some(f=>/DATE|EVIDENCE|OWNERSHIP|INVITATION|EXCEPTION|REVIEW|IDENTITY|PROOF/.test(f.code))?"CURRENT":"REPAIR_REQUIRED"},unresolved_count:findings.length+(r.external_requests||[]).filter(x=>!x.blocking&&x.status==="OPEN").length,findings,source:r}; } export function importEnvelope(value){const source=value?.schema_version===SCHEMA_VERSION?value:value?.schema_version==="maestro.linkedin-business-manager.evaluation.v2"?value.source:null;if(!source)throw new Error("Import requires a v2 source or evaluation envelope");return evaluate(source);} const md=v=>v===null||v===undefined?"":String(v).replaceAll("\n"," "); const compact=v=>JSON.stringify(v??null); export function toMarkdown(value){ const e=importEnvelope(value),c=e.asset_coverage,o=e.source.organization,a=e.source.assignee,proof=id=>e.source.evidence.find(x=>x.evidence_id===id)||null; const lines=["# LinkedIn Business Manager access handoff","",`- Record: ${md(e.record_id)}`,`- Revision: ${e.revision}`,`- Schema: ${md(e.source.schema_version)}; contract ${md(e.contract_version)}`,`- Fictional: ${e.fictional}`,`- State: ${e.state}`,`- Reason: ${e.reason}`,`- Next action: ${e.next_action}`,`- Coverage: ${c.required} required / ${c.ownership} owned or shared / ${c.requested} requested / ${c.approved} approved / ${c.verified} verified`,`- Freshness: ${e.evidence_freshness.status}`,`- Reviewed: ${e.evidence_freshness.reviewed_at}; max age ${e.evidence_freshness.max_evidence_age_days} days`,"","## Organization and assignee","",`- Organization: ${md(o.name)}; ${md(o.controlling_organization_id)}`,`- Business Manager: ${md(o.business_manager_name)}; ${md(o.business_manager_id)}`,`- Business Manager ownership: ${md(o.ownership_event_at)}; evidence ${md(o.ownership_evidence_id)}; ${md(proof(o.ownership_evidence_id)?.reference)}`,`- Assignee: ${md(a.name)}; ${md(a.assignee_id)}; ${md(a.type)}; organization ${md(a.organization_id)}; Business Manager role ${md(a.business_manager_role)}`,`- Partner Business Manager: ${md(a.partner_business_manager_id)}; separate organization ${a.separate_organization}`,`- Invitation: ${md(a.invitation_status)}; event ${md(a.invitation_event_at)}; evidence ${md(a.invitation_evidence_id)}; ${md(proof(a.invitation_evidence_id)?.reference)}`,`- Admin exception: ${md(a.admin_exception?.reason_code)}; ${md(a.admin_exception?.decision)}; reviewer ${md(a.admin_exception?.reviewer_id)}; decided ${md(a.admin_exception?.decided_at)}; expires ${md(a.admin_exception?.expires_at)}; evidence ${md(a.admin_exception?.evidence_id)}; ${md(proof(a.admin_exception?.evidence_id)?.reference)}`,"","## Identity registry",""]; for(const x of e.source.identities){const p=proof(x.verification_evidence_id);lines.push(`- ${md(x.identity_id)}: ${md(x.name)}; ${md(x.type)}; organization ${md(x.organization_id)}; authorized approver ${x.authorized_approver}; trust root ${x.trust_root}; verification ${md(x.verification_evidence_id)}; event ${md(p?.event_at)}; captured ${md(p?.captured_at)}; custodian ${md(p?.owner_id)}; ${md(p?.reference)}`);} lines.push("","## Assets",""); for(const asset of e.source.assets){const n=e.node_status.find(x=>x.asset_id===asset.asset_id)||{},ids=[asset.ownership_evidence_id,asset.role_exception?.evidence_id,asset.request.evidence_id,asset.approval.evidence_id,asset.verification.evidence_id].filter(Boolean);lines.push(`### ${md(asset.name||asset.asset_id)}`,"",`- IDs: ${md(asset.asset_id)} / ${md(asset.native_id)}`,`- Relationship: ${md(asset.relationship)}; asserted owner ${md(asset.owner_organization_id)}`,`- Required capabilities: ${(asset.required_capabilities||[]).join(", ")}`,`- Prohibited capabilities: ${(asset.prohibited_capabilities||[]).join(", ")||"None"}`,`- Role: ${md(asset.requested_role)} (${md(asset.scope_decision)})`,`- Role exception: ${md(asset.role_exception?.reason_code)}; ${md(asset.role_exception?.decision)}; reviewer ${md(asset.role_exception?.reviewer_id)}; decided ${md(asset.role_exception?.decided_at)}; expires ${md(asset.role_exception?.expires_at)}; evidence ${md(asset.role_exception?.evidence_id)}`,`- Computed nodes: ownership ${!!n.ownership}; role ${!!n.role}; request ${!!n.request}; approval ${!!n.approval}; verification ${!!n.verification}`,`- Ownership: ${md(asset.ownership_event_at)}; evidence ${md(asset.ownership_evidence_id)}`,`- Request: ${md(asset.request.status)}; ${md(asset.request.requester_id)} -> ${md(asset.request.approver_id)}; ${md(asset.request.event_at)}; evidence ${md(asset.request.evidence_id)}`,`- Approval: ${md(asset.approval.decision)}; ${md(asset.approval.approver_id)}; ${md(asset.approval.approved_role)}; ${md(asset.approval.event_at)}; evidence ${md(asset.approval.evidence_id)}`,`- Verification claim: ${md(asset.verification.outcome)}; computed ${!!n.verification}; ${md(asset.verification.task_template_id)}; ${md(asset.verification.assignee_id)}; ${md(asset.verification.event_at)}; evidence ${md(asset.verification.evidence_id)}`);for(const id of ids){const evi=proof(id);if(evi)lines.push(`- Evidence ${md(id)}: ${md(evi.kind)}; subject ${md(evi.subject_type)} ${md(evi.subject_id)}; actor ${md(evi.actor_id)}; capability ${md(evi.capability)}; template ${md(evi.task_template_id)}; asserted owner ${md(evi.asserted_owner_organization_id)}; recipient ${md(evi.recipient_organization_id)}; event ${md(evi.event_at)}; captured ${md(evi.captured_at)}; custodian ${md(evi.owner_id)}; ${md(evi.reference)}`);}for(const note of asset.notes||[])lines.push(`- Note: ${md(note)}`);lines.push("");} lines.push("## Verification observations","",...e.source.assets.map(x=>`- ${md(x.asset_id)}: claim ${md(x.verification?.outcome)}; observations valid ${x.verification?.observations_valid}`),""); lines.push("## Evidence ledger","",...e.source.evidence.map(x=>`- ${md(x.evidence_id)}: ${md(x.kind)}; subject ${md(x.subject_type)} ${md(x.subject_id)}; actor ${md(x.actor_id)}; capability ${md(x.capability)}; template ${md(x.task_template_id)}; asserted owner ${md(x.asserted_owner_organization_id)}; recipient ${md(x.recipient_organization_id)}; event ${md(x.event_at)}; captured ${md(x.captured_at)}; custodian ${md(x.owner_id)}; ${md(x.reference)}`),"","## External requests","",...(e.source.external_requests.length?e.source.external_requests.map(x=>`- ${md(x.request_id)}: ${md(x.status)}; blocking ${x.blocking}; global ${x.global_blocker}; owner ${md(x.owner_id)}; next action ${md(x.next_action)}; blocked nodes ${(x.blocked_nodes||[]).map(n=>`${n.asset_id}:${n.node}`).join(", ")||"global"}`):["- None."]),"","## Findings","",...(e.findings.length?e.findings.map(f=>`- ${f.code}: ${f.reason} Next: ${f.next_action}`):["- None."]),"","## Notes","",...(e.source.notes.length?e.source.notes.map(x=>`- ${md(x)}`):["- None."]),"","Notes are preserved but never determine state.","");return lines.join("\n"); } export function toAssetCsv(value){ const e=importEnvelope(value),o=e.source.organization,a0=e.source.assignee,proof=id=>e.source.evidence.find(x=>x.evidence_id===id)||{},identitiesJson=compact(e.source.identities),identityProofsJson=compact(e.source.identities.map(x=>({identity:x,proof:proof(x.verification_evidence_id)}))),externalJson=compact(e.source.external_requests),unresolvedJson=compact(e.source.external_requests.filter(x=>x.status==="OPEN")); const receiptHeaders=prefix=>["reference","event_at","captured_at","subject_type","subject_id","actor_id","custodian_id","capability","task_template_id","asserted_owner_organization_id","recipient_organization_id","json"].map(x=>`${prefix}_${x}`),receiptValues=p=>[p.reference,p.event_at,p.captured_at,p.subject_type,p.subject_id,p.actor_id,p.owner_id,p.capability,p.task_template_id,p.asserted_owner_organization_id,p.recipient_organization_id,compact(p)]; const h=["record_id","revision","source_schema_version","contract_version","evaluation_state","evaluation_reason","evaluation_next_action","evidence_freshness_status","findings_json","assets_json","all_evidence_json","fictional","organization_name","business_manager_name","controlling_organization_id","business_manager_id","business_manager_ownership_evidence_id","business_manager_ownership_asserted_event_at",...receiptHeaders("business_manager_ownership"),"assignee_id","assignee_name","assignee_type","assignee_organization_id","assignee_business_manager_role","assignee_trust_root_identity_ids_json","assignee_partner_business_manager_id","assignee_separate_organization","invitation_status","invitation_event_at","invitation_evidence_id",...receiptHeaders("invitation_evidence"),"admin_exception_reason","admin_exception_decision","admin_exception_reviewer_id","admin_exception_decided_at","admin_exception_expires_at","admin_exception_evidence_id",...receiptHeaders("admin_exception_evidence"),"identities_json","identity_proofs_and_custodians_json","external_requests_json","unresolved_external_actions_json","asset_id","native_id","relationship","owner_organization_id","task_code","required_capabilities","prohibited_capabilities","requested_role","scope_decision","role_exception_reason","role_exception_decision","role_exception_reviewer_id","role_exception_decided_at","role_exception_expires_at","role_exception_evidence_id",...receiptHeaders("role_exception_evidence"),"ownership_event_at","ownership_evidence_id",...receiptHeaders("ownership_evidence"),"request_status","requester_id","intended_approver_id","request_event_at","request_evidence_id",...receiptHeaders("request_evidence"),"approval_decision","approver_id","approved_role","approval_event_at","approval_evidence_id",...receiptHeaders("approval_evidence"),"verification_claim","task_template_id","assignee_id_for_check","verification_event_at","verification_evidence_id",...receiptHeaders("verification_evidence"),"node_ownership","node_role","node_request","node_approval","node_verification"]; const q=v=>`"${String(v??"").replaceAll('"','""')}"`,rows=[h.join(",")]; for(const asset of e.source.assets){const node=e.node_status.find(x=>x.asset_id===asset.asset_id)||{},own=proof(asset.ownership_evidence_id),req=proof(asset.request.evidence_id),app=proof(asset.approval.evidence_id),ver=proof(asset.verification.evidence_id),ex=proof(asset.role_exception?.evidence_id),admin=a0.admin_exception||{},adminProof=proof(admin.evidence_id),orgProof=proof(o.ownership_evidence_id),inviteProof=proof(a0.invitation_evidence_id);const row=[e.fictional,o.name,o.business_manager_name,o.controlling_organization_id,o.business_manager_id,o.ownership_evidence_id,o.ownership_event_at,...receiptValues(orgProof),a0.assignee_id,a0.name,a0.type,a0.organization_id,a0.business_manager_role,compact(e.source.identities.filter(x=>x.trust_root).map(x=>x.identity_id)),a0.partner_business_manager_id,a0.separate_organization,a0.invitation_status,a0.invitation_event_at,a0.invitation_evidence_id,...receiptValues(inviteProof),admin.reason_code,admin.decision,admin.reviewer_id,admin.decided_at,admin.expires_at,admin.evidence_id,...receiptValues(adminProof),identitiesJson,identityProofsJson,externalJson,unresolvedJson,asset.asset_id,asset.native_id,asset.relationship,asset.owner_organization_id,asset.task_code,(asset.required_capabilities||[]).join("|"),(asset.prohibited_capabilities||[]).join("|"),asset.requested_role,asset.scope_decision,asset.role_exception?.reason_code,asset.role_exception?.decision,asset.role_exception?.reviewer_id,asset.role_exception?.decided_at,asset.role_exception?.expires_at,asset.role_exception?.evidence_id,...receiptValues(ex),asset.ownership_event_at,asset.ownership_evidence_id,...receiptValues(own),asset.request.status,asset.request.requester_id,asset.request.approver_id,asset.request.event_at,asset.request.evidence_id,...receiptValues(req),asset.approval.decision,asset.approval.approver_id,asset.approval.approved_role,asset.approval.event_at,asset.approval.evidence_id,...receiptValues(app),asset.verification.outcome,asset.verification.task_template_id,asset.verification.assignee_id,asset.verification.event_at,asset.verification.evidence_id,...receiptValues(ver),node.ownership,node.role,node.request,node.approval,node.verification];rows.push([e.record_id,e.revision,e.source.schema_version,e.contract_version,e.state,e.reason,e.next_action,e.evidence_freshness.status,compact(e.findings),compact(e.source.assets),compact(e.source.evidence)].map(q).concat(row.map(q)).join(","));} return rows.join("\n")+"\n"; } ```