Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : packages/contracts/src/index.ts9 * Module : contracts10 * Repository : https://git.spboucher.ai/maclustr-social11 * Project Website : https://social.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Shared typed contracts: state machines, DSL, API payloads. No I/O here.43import { z } from 'zod';44export { z };4546/* ───────────── Navigator session states ───────────── */47export const SESSION_STATES = ['UNINITIALIZED', 'LOGIN_REQUIRED', 'MANUAL_CONTROL', 'READY', 'BUSY', 'SECURITY_CHALLENGE', 'EXPIRED', 'PAUSED', 'FAILED', 'REVOKED'] as const;48export const SessionState = z.enum(SESSION_STATES);49export type SessionState = z.infer<typeof SessionState>;5051export const SESSION_TRANSITIONS: Record<SessionState, SessionState[]> = {52 UNINITIALIZED: ['LOGIN_REQUIRED', 'MANUAL_CONTROL', 'PAUSED', 'FAILED', 'REVOKED'],53 LOGIN_REQUIRED: ['MANUAL_CONTROL', 'PAUSED', 'EXPIRED', 'FAILED', 'REVOKED'],54 MANUAL_CONTROL: ['READY', 'LOGIN_REQUIRED', 'SECURITY_CHALLENGE', 'PAUSED', 'EXPIRED', 'FAILED', 'REVOKED'],55 READY: ['BUSY', 'MANUAL_CONTROL', 'LOGIN_REQUIRED', 'SECURITY_CHALLENGE', 'PAUSED', 'EXPIRED', 'FAILED', 'REVOKED'],56 BUSY: ['READY', 'MANUAL_CONTROL', 'LOGIN_REQUIRED', 'SECURITY_CHALLENGE', 'PAUSED', 'EXPIRED', 'FAILED', 'REVOKED'],57 SECURITY_CHALLENGE: ['MANUAL_CONTROL', 'LOGIN_REQUIRED', 'PAUSED', 'EXPIRED', 'FAILED', 'REVOKED'],58 EXPIRED: ['LOGIN_REQUIRED', 'MANUAL_CONTROL', 'PAUSED', 'REVOKED'],59 PAUSED: ['LOGIN_REQUIRED', 'MANUAL_CONTROL', 'READY', 'FAILED', 'REVOKED'],60 FAILED: ['UNINITIALIZED', 'LOGIN_REQUIRED', 'PAUSED', 'REVOKED'],61 REVOKED: [],62};63export function canTransitionSession(from: SessionState, to: SessionState): boolean {64 return SESSION_TRANSITIONS[from].includes(to);65}66/** States in which no agent step, capture or recording may run. */67export const AGENT_FORBIDDEN_STATES: SessionState[] = ['UNINITIALIZED', 'LOGIN_REQUIRED', 'MANUAL_CONTROL', 'SECURITY_CHALLENGE', 'EXPIRED', 'PAUSED', 'FAILED', 'REVOKED'];6869/* ───────────── Publication states ───────────── */70export const PUBLICATION_STATES = ['DRAFT', 'REVIEW', 'APPROVED', 'QUEUED', 'PREPARING', 'AWAITING_CONFIRMATION', 'SUBMITTED', 'VERIFIED', 'UNKNOWN_OUTCOME', 'FAILED', 'CANCELLED'] as const;71export const PublicationState = z.enum(PUBLICATION_STATES);72export type PublicationState = z.infer<typeof PublicationState>;73export const CONTENT_STATES = ['DRAFT', 'REVIEW', 'APPROVED'] as const;74export const JOB_STATES = ['QUEUED', 'PREPARING', 'AWAITING_CONFIRMATION', 'SUBMITTED', 'VERIFIED', 'UNKNOWN_OUTCOME', 'FAILED', 'CANCELLED'] as const;75export type JobState = (typeof JOB_STATES)[number];76export const JOB_TRANSITIONS: Record<JobState, JobState[]> = {77 QUEUED: ['PREPARING', 'AWAITING_CONFIRMATION', 'CANCELLED', 'FAILED'],78 PREPARING: ['AWAITING_CONFIRMATION', 'QUEUED', 'FAILED', 'CANCELLED'],79 AWAITING_CONFIRMATION: ['SUBMITTED', 'UNKNOWN_OUTCOME', 'CANCELLED', 'FAILED'],80 SUBMITTED: ['VERIFIED', 'UNKNOWN_OUTCOME'],81 UNKNOWN_OUTCOME: ['VERIFIED', 'FAILED'], // manual reconciliation only82 VERIFIED: [], FAILED: [], CANCELLED: [],83};84export function canTransitionJob(from: JobState, to: JobState): boolean {85 return JOB_TRANSITIONS[from].includes(to);86}87export const JOB_MODES = ['manual_assisted', 'prepare_only', 'auto_submit'] as const;88export type JobMode = (typeof JOB_MODES)[number];8990/* ───────────── Roles ───────────── */91export const ROLES = ['owner', 'admin', 'approver', 'editor', 'viewer'] as const;92export type Role = (typeof ROLES)[number];93export const ROLE_RANK: Record<Role, number> = { viewer: 1, editor: 2, approver: 3, admin: 4, owner: 5 };9495/* ───────────── Content hash ───────────── */96export const ContentPayload = z.object({97 lang: z.enum(['fr', 'en']),98 body: z.string().min(1).max(8000),99 linkUrl: z.string().url().max(2000).nullable().default(null),100 mediaSha256: z.array(z.string().regex(/^[a-f0-9]{64}$/)).max(10).default([]),101 altText: z.string().max(1000).nullable().default(null),102}).strict();103export type ContentPayload = z.infer<typeof ContentPayload>;104/** Canonical JSON used for the approval hash: fixed key order, NFC text. */105export function canonicalContent(c: ContentPayload): string {106 return JSON.stringify({107 altText: c.altText ? c.altText.normalize('NFC') : null,108 body: c.body.normalize('NFC'),109 lang: c.lang,110 linkUrl: c.linkUrl ?? null,111 mediaSha256: [...c.mediaSha256],112 });113}114115/* ───────────── Navigator DSL ───────────── */116const Tpl = z.string().min(1).max(4000);117export const Locator = z.union([118 z.object({ role: z.enum(['button', 'link', 'textbox', 'combobox', 'checkbox', 'radio', 'tab', 'menuitem', 'dialog', 'heading', 'option', 'article', 'listitem', 'img', 'status', 'alert', 'navigation', 'main']), name: Tpl.optional(), exact: z.boolean().optional(), within: z.object({ role: z.enum(['dialog', 'article', 'navigation', 'main']), name: Tpl.optional() }).strict().optional() }).strict(),119 z.object({ label: Tpl, exact: z.boolean().optional() }).strict(),120 z.object({ text: Tpl, exact: z.boolean().optional() }).strict(),121 z.object({ placeholder: Tpl }).strict(),122 z.object({ testId: z.string().regex(/^[A-Za-z0-9_-]{1,80}$/) }).strict(),123]);124export type Locator = z.infer<typeof Locator>;125export const Condition = z.discriminatedUnion('kind', [126 z.object({ kind: z.literal('urlStartsWith'), value: Tpl }).strict(),127 z.object({ kind: z.literal('visible'), locator: Locator }).strict(),128 z.object({ kind: z.literal('hidden'), locator: Locator }).strict(),129 z.object({ kind: z.literal('textVisible'), text: Tpl }).strict(),130 z.object({ kind: z.literal('valueEquals'), locator: Locator, value: Tpl }).strict(),131]);132export type Condition = z.infer<typeof Condition>;133const base = { id: z.string().regex(/^[a-z0-9_-]{1,40}$/), timeoutMs: z.number().int().min(100).max(120_000), pre: z.array(Condition).max(8).optional(), post: z.array(Condition).max(8).optional(), note: z.string().max(300).optional(), when: z.enum(['content.hasMedia', 'content.hasLink']).optional() };134export const Action = z.discriminatedUnion('action', [135 z.object({ action: z.literal('navigate'), ...base, url: Tpl }).strict(),136 z.object({ action: z.literal('inspect'), ...base, locator: Locator, read: z.enum(['text', 'value', 'count', 'href']), as: z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,30}$/) }).strict(),137 z.object({ action: z.literal('click'), ...base, locator: Locator, effect: z.enum(['none', 'external_submit']).default('none') }).strict(),138 z.object({ action: z.literal('fill'), ...base, locator: Locator, value: Tpl }).strict(),139 z.object({ action: z.literal('select'), ...base, locator: Locator, option: Tpl }).strict(),140 z.object({ action: z.literal('uploadApprovedMedia'), ...base, locator: Locator }).strict(),141 z.object({ action: z.literal('waitFor'), ...base, cond: Condition }).strict(),142 z.object({ action: z.literal('captureRedacted'), ...base, label: z.string().regex(/^[a-z0-9_-]{1,40}$/), mask: z.array(Locator).max(10).optional() }).strict(),143 z.object({ action: z.literal('assertPage'), ...base, expectedName: Tpl.optional(), expectedExternalId: Tpl.optional(), nameLocator: Locator.optional() }).strict(),144 z.object({ action: z.literal('requestApproval'), ...base, reason: z.string().max(300) }).strict(),145 z.object({ action: z.literal('stop'), ...base, reason: z.string().max(300) }).strict(),146]);147export type Action = z.infer<typeof Action>;148export const ACTION_NAMES = ['navigate', 'inspect', 'click', 'fill', 'select', 'uploadApprovedMedia', 'waitFor', 'captureRedacted', 'assertPage', 'requestApproval', 'stop'] as const;149export const RecipeDefinition = z.object({150 slug: z.string().regex(/^[a-z0-9-]{3,60}$/),151 title: z.string().max(200),152 purpose: z.enum(['prepare_composer', 'submit', 'verify_result', 'read_comments', 'read_metrics', 'health_check']),153 /** Host suffixes this recipe may touch; the engine refuses anything else. */154 allowedHosts: z.array(z.string().regex(/^[a-z0-9.:-]{3,120}$/)).min(1).max(10),155 steps: z.array(Action).min(1).max(60),156}).strict();157export type RecipeDefinition = z.infer<typeof RecipeDefinition>;158/** Variables a recipe template may reference. Anything else is refused at validation time. */159export const TEMPLATE_VARS = ['page.url', 'page.composerUrl', 'page.name', 'page.externalId', 'content.body', 'content.linkUrl', 'content.altText', 'content.firstLine'] as const;160161/* ───────────── API payloads ───────────── */162export const Uuid = z.string().uuid();163export const BrandInput = z.object({164 slug: z.string().regex(/^[a-z0-9-]{2,40}$/), name: z.string().min(1).max(120),165 tone: z.string().max(2000).default(''), languages: z.array(z.enum(['fr', 'en'])).min(1).default(['fr']),166 officialUrls: z.array(z.string().url()).max(20).default([]), categories: z.array(z.string().max(60)).max(40).default([]),167 identity: z.object({ primary: z.string().regex(/^#[0-9a-fA-F]{6}$/), ink: z.string().regex(/^#[0-9a-fA-F]{6}$/), paper: z.string().regex(/^#[0-9a-fA-F]{6}$/), wordmark: z.string().max(60) }).strict(),168 frequency: z.object({ maxPerDay: z.number().int().min(0).max(20), minIntervalMinutes: z.number().int().min(0).max(10080) }).strict().default({ maxPerDay: 1, minIntervalMinutes: 240 }),169 validation: z.object({ approvalsRequired: z.number().int().min(1).max(3), allowSelfApproval: z.boolean() }).strict().default({ approvalsRequired: 1, allowSelfApproval: false }),170 timezone: z.string().max(60).default('America/Toronto'),171}).strict();172export type BrandInput = z.infer<typeof BrandInput>;173export const PageInput = z.object({ brandId: Uuid, platform: z.enum(['facebook', 'fixture']), displayName: z.string().min(1).max(200), url: z.string().url().max(500), composerUrl: z.string().url().max(500).nullable().default(null), externalPageId: z.string().regex(/^[A-Za-z0-9._-]{1,80}$/).nullable().default(null) }).strict();174export const ContentCreate = z.object({ brandId: Uuid, pageId: Uuid.nullable().default(null), campaignId: Uuid.nullable().default(null), title: z.string().min(1).max(200), payload: ContentPayload, sourceEventId: Uuid.nullable().default(null) }).strict();175export const ContentUpdate = z.object({ title: z.string().min(1).max(200).optional(), pageId: Uuid.nullable().optional(), payload: ContentPayload.optional() }).strict();176export const ApproveInput = z.object({ versionId: Uuid, contentHash: z.string().regex(/^[a-f0-9]{64}$/), pageId: Uuid, decision: z.enum(['approve', 'reject']), comment: z.string().max(1000).default('') }).strict();177export const JobCreate = z.object({ contentId: Uuid, scheduledAt: z.string().datetime(), mode: z.enum(JOB_MODES).default('manual_assisted') }).strict();178export const JobReconcile = z.object({ outcome: z.enum(['published', 'not_published']), externalUrl: z.string().url().max(1000).nullable().default(null), note: z.string().max(1000).default('') }).strict();179export const SessionCreate = z.object({ label: z.string().min(1).max(80), workerId: Uuid, startUrl: z.string().url().max(500).optional() }).strict();180export const SessionConfirm = z.object({ pageIds: z.array(Uuid).min(1).max(20), attest: z.literal(true) }).strict();181export const WorkerHeartbeat = z.object({ sessions: z.array(z.object({ sessionId: Uuid, observed: z.enum(['running', 'stopped', 'login_required', 'security_challenge', 'ok']), url: z.string().max(2000).optional() }).strict()).max(50).default([]), info: z.object({ version: z.string().max(40), headed: z.boolean(), freeDiskGb: z.number().optional(), axPermission: z.boolean().optional(), screenPermission: z.boolean().optional() }).strict() }).strict();182export const EmergencyStop = z.object({ engage: z.boolean(), reason: z.string().min(3).max(500) }).strict();183export const CampaignInput = z.object({ brandId: Uuid, name: z.string().min(1).max(160), objective: z.string().max(2000).default(''), startsAt: z.string().datetime().nullable().default(null), endsAt: z.string().datetime().nullable().default(null) }).strict();184export const CommentImport = z.object({ pageId: Uuid, items: z.array(z.object({ externalRef: z.string().max(200), body: z.string().min(1).max(5000), capturedAt: z.string().datetime().optional() }).strict()).min(1).max(200) }).strict();185export const MetricImport = z.object({ pageId: Uuid, contentId: Uuid.nullable().default(null), periodStart: z.string().datetime(), periodEnd: z.string().datetime(), source: z.string().min(2).max(200), metrics: z.array(z.object({ metric: z.enum(['reach', 'impressions', 'interactions', 'reactions', 'comments', 'shares', 'link_clicks', 'followers']), value: z.number().nonnegative().nullable() }).strict()).min(1).max(20) }).strict();186export const AgentRunInput = z.object({ agent: z.enum(['director', 'product', 'copywriter', 'creative', 'fact_checker', 'compliance', 'publisher', 'community', 'analytics', 'supervisor']), brandId: Uuid.nullable().default(null), contentId: Uuid.nullable().default(null), commentId: Uuid.nullable().default(null), sourceEventId: Uuid.nullable().default(null), instruction: z.string().max(4000).default('') }).strict();187188/* ───────────── Navigator wire protocol (viewer ⇄ gateway ⇄ worker) ───────────── */189export const ViewerMsg = z.discriminatedUnion('t', [190 z.object({ t: z.literal('mouse'), type: z.enum(['move', 'down', 'up', 'wheel']), x: z.number().min(0).max(8192), y: z.number().min(0).max(8192), button: z.enum(['left', 'middle', 'right', 'none']).default('none'), dx: z.number().min(-5000).max(5000).default(0), dy: z.number().min(-5000).max(5000).default(0), clicks: z.number().int().min(0).max(3).default(0), mods: z.number().int().min(0).max(15).default(0) }).strict(),191 z.object({ t: z.literal('key'), type: z.enum(['down', 'up']), key: z.string().max(32), code: z.string().max(32), mods: z.number().int().min(0).max(15).default(0) }).strict(),192 z.object({ t: z.literal('text'), text: z.string().max(200) }).strict(),193 z.object({ t: z.literal('touch'), type: z.enum(['start', 'move', 'end', 'cancel']), points: z.array(z.object({ x: z.number().min(0).max(8192), y: z.number().min(0).max(8192), id: z.number().int().min(0).max(20) }).strict()).max(5) }).strict(),194 z.object({ t: z.literal('resize'), w: z.number().int().min(320).max(2560), h: z.number().int().min(320).max(1600), dpr: z.number().min(1).max(3).default(1), mobile: z.boolean().default(false) }).strict(),195 z.object({ t: z.literal('nav'), op: z.enum(['back', 'forward', 'reload', 'goto']), url: z.string().url().max(2000).optional() }).strict(),196 z.object({ t: z.literal('tab'), op: z.enum(['activate', 'close']), tabId: z.string().max(40) }).strict(),197 z.object({ t: z.literal('zoom'), factor: z.number().min(0.5).max(3) }).strict(),198 z.object({ t: z.literal('insertApproved'), jobId: Uuid }).strict(),199 z.object({ t: z.literal('chooseMedia'), jobId: Uuid }).strict(),200 z.object({ t: z.literal('cancelChooser') }).strict(),201 z.object({ t: z.literal('ack'), frame: z.number().int() }).strict(),202 z.object({ t: z.literal('ping'), n: z.number() }).strict(),203]);204export type ViewerMsg = z.infer<typeof ViewerMsg>;205export const INPUT_MSG_TYPES = new Set(['mouse', 'key', 'text', 'touch', 'nav', 'tab', 'insertApproved', 'chooseMedia', 'cancelChooser', 'zoom']);206207export type ApiError = { error: { code: string; message: string; correlationId?: string; details?: unknown } };208