{
  "version": 3,
  "sources": ["../../../../src/logic-functions/uninstall.logic-function.ts", "twenty-sdk-define-stub:__twenty-sdk-define-stub__", "../../../../src/constants/logic-function-identifiers.ts", "../../../../src/logic-functions/greenlight-api.ts", "../../../../src/enrichment/field-specs.ts", "../../../../src/scoring/types.ts", "../../../../src/logic-functions/greenlight-config-record.ts", "../../../../src/logic-functions/install-run.ts"],
  "sourcesContent": ["import { CoreApiClient } from 'twenty-client-sdk/core';\nimport {\n  defineUninstallLogicFunction,\n  type UninstallPayload,\n} from 'twenty-sdk/define';\n\nimport { UNINSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/logic-function-identifiers';\nimport { runUninstall } from 'src/logic-functions/install-run';\n\n/**\n * Uninstall hook \u2014 and an honest account of what it can and cannot do.\n *\n * ## What the payload actually gives us\n *\n * `UninstallPayload` is `{ version?: string }`. Nothing else. It does not\n * enumerate the objects the app created, the fields it grafted onto Person, or\n * the records it wrote. Any design that assumed \"the hook is told what to clean\n * up\" has to be rewritten around that, and this one is.\n *\n * ## What this hook CANNOT clean up\n *\n * * **`GreenlightConfig` and `GreenlightAuditLog` objects and their records.**\n *   They are app-owned metadata; the deletion migration that runs immediately\n *   after this hook removes them. The hook could delete the rows first, which\n *   would achieve nothing except spending an uninstall's patience on rows that\n *   are about to be dropped anyway.\n * * **The three fields on Person (`greenlightScore`, `greenlightDecision`,\n *   `greenlightTrace`) and their values.** Same reason: they are app-owned field\n *   metadata on a standard object, and they go with the app. Nulling them first\n *   would mean an unbounded write over every Person in the workspace \u2014 hundreds\n *   of thousands of rows in a large CRM \u2014 inside a best-effort hook that must\n *   never delay an uninstall.\n * * **Preserving the audit trail past uninstall.** There is nowhere to put it.\n *   The hook can read the rows but has no destination that survives the app;\n *   exporting them to an external service would be a data-egress channel the DPA\n *   does not declare. A workspace that wants the trail must export it *before*\n *   uninstalling.\n * * **Listeners / trigger registrations.** Owned by the platform, removed with\n *   the app manifest.\n *\n * ## What this hook CAN do, and does\n *\n * * Emit one structured log line recording the version being removed and how\n *   much configuration was in place, so the server log retains a marker after\n *   every trace of the app is gone.\n * * Fail silently. It is documented as best-effort \u2014 \"a failure is logged and\n *   never blocks the uninstall\" \u2014 and this implementation never throws, so it\n *   cannot make the app hard to remove.\n *\n * ## Why ship it at all, then\n *\n * Two reasons, both about the future rather than v0.1. First, the\n * `universalIdentifier` is permanent, and minting it now means the hook can gain\n * behaviour in a later release without a new registration. Second, this is the\n * only place external deprovisioning can ever live: when licensing lands, the\n * licence must be *deactivated* here (freeing the customer's activation slot)\n * while the workspace id is still readable. That work cannot be moved to an\n * external scheduled job, because after uninstall there is no app data left to\n * tell the job which licence to release.\n *\n * ## ARCHITECTURE.md is wrong about this\n *\n * Its \"Upgrade & Uninstall\" section lists \"Delete GreenlightConfig +\n * GreenlightAuditLog objects\", \"Remove score/gate fields from Lead object\" and\n * \"Unregister listeners\" as uninstall steps. All three are the platform's work,\n * not the app's, and none of them is expressible from a hook holding only a\n * version string. Its final bullet \u2014 \"Keep audit trail (Twenty CRM's\n * deleted-object backups retain it)\" \u2014 is an unverified claim about Twenty's\n * retention behaviour and should not be repeated in a security or DPA document.\n */\nconst handler = async (payload: UninstallPayload) =>\n  runUninstall({\n    client: new CoreApiClient(),\n    payload,\n  });\n\nexport default defineUninstallLogicFunction({\n  universalIdentifier: UNINSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,\n  name: 'greenlight-uninstall',\n  description:\n    'Records the uninstall in the server log. Greenlight v0.1 provisions no external resources, so there is nothing else to deprovision.',\n  // 30s, well under the 300s default. This hook runs synchronously inside the\n  // uninstall flow and does one read; anything longer would only extend how long\n  // a user waits to remove an app that is already on its way out.\n  timeoutSeconds: 30,\n  handler,\n});\n", "\n// Auto-generated stub for twenty-sdk/define injected by the SDK CLI build.\n// Real implementations would pull in zod, twenty-shared and ~1MB of code; at\n// runtime only `default.config.handler` is consumed, so tiny no-ops suffice.\nconst __defineFactoryStub = (config) => ({\n  success: true,\n  config,\n  errors: [],\n});\n\nconst __anyHandler = {\n  get(_target, prop) {\n    if (prop === '__esModule') return true;\n    if (prop === Symbol.toPrimitive) return () => '';\n    if (typeof prop === 'symbol') return undefined;\n    return new Proxy(() => undefined, __anyHandler);\n  },\n  apply() {\n    return new Proxy(() => undefined, __anyHandler);\n  },\n};\nconst __anyStub = new Proxy(() => undefined, __anyHandler);\n\nexport const createValidationResult = __defineFactoryStub;\nexport const defineAgent = __defineFactoryStub;\nexport const defineApplication = __defineFactoryStub;\nexport const defineApplicationRole = __defineFactoryStub;\nexport const defineCommandMenuItem = __defineFactoryStub;\nexport const defineConnectionProvider = __defineFactoryStub;\nexport const defineField = __defineFactoryStub;\nexport const defineFrontComponent = __defineFactoryStub;\nexport const defineIndex = __defineFactoryStub;\nexport const defineLogicFunction = __defineFactoryStub;\nexport const defineNavigationMenuItem = __defineFactoryStub;\nexport const defineObject = __defineFactoryStub;\nexport const definePageLayout = __defineFactoryStub;\nexport const definePageLayoutTab = __defineFactoryStub;\nexport const definePermissionFlag = __defineFactoryStub;\nexport const definePostInstallLogicFunction = __defineFactoryStub;\nexport const definePreInstallLogicFunction = __defineFactoryStub;\nexport const defineRole = __defineFactoryStub;\nexport const defineSettingsFrontComponent = __defineFactoryStub;\nexport const defineSkill = __defineFactoryStub;\nexport const defineUninstallLogicFunction = __defineFactoryStub;\nexport const defineView = __defineFactoryStub;\nexport const defineViewField = __defineFactoryStub;\nexport const AggregateOperations = __anyStub;\nexport const DateDisplayFormat = __anyStub;\nexport const FieldMetadataSettingsOnClickAction = __anyStub;\nexport const FieldType = __anyStub;\nexport const HTTPMethod = __anyStub;\nexport const NavigationMenuItemType = __anyStub;\nexport const NumberDataType = __anyStub;\nexport const ObjectRecordGroupByDateGranularity = __anyStub;\nexport const OnDeleteAction = __anyStub;\nexport const PageLayoutTabLayoutMode = __anyStub;\nexport const PageLayoutType = __anyStub;\nexport const RelationType = __anyStub;\nexport const RowLevelPermissionPredicateGroupLogicalOperator = __anyStub;\nexport const RowLevelPermissionPredicateOperand = __anyStub;\nexport const STANDARD_OBJECT = __anyStub;\nexport const STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS = __anyStub;\nexport const STANDARD_PAGE_LAYOUT = __anyStub;\nexport const STANDARD_PAGE_LAYOUT_UNIVERSAL_IDENTIFIERS = __anyStub;\nexport const SystemPermissionFlag = __anyStub;\nexport const ViewCalendarLayout = __anyStub;\nexport const ViewFilterGroupLogicalOperator = __anyStub;\nexport const ViewFilterOperand = __anyStub;\nexport const ViewKey = __anyStub;\nexport const ViewOpenRecordIn = __anyStub;\nexport const ViewSortDirection = __anyStub;\nexport const ViewType = __anyStub;\nexport const ViewVisibility = __anyStub;\nexport const canAccessFullAdminPanel = __anyStub;\nexport const canImpersonate = __anyStub;\nexport const every = __anyStub;\nexport const everyDefined = __anyStub;\nexport const everyEquals = __anyStub;\nexport const favoriteRecordIds = __anyStub;\nexport const featureFlags = __anyStub;\nexport const getFieldUniversalIdentifier = __anyStub;\nexport const getSystemRelationFieldUniversalIdentifier = __anyStub;\nexport const getSystemViewFieldUniversalIdentifier = __anyStub;\nexport const getSystemViewUniversalIdentifier = __anyStub;\nexport const hasAnySoftDeleteFilterOnView = __anyStub;\nexport const includes = __anyStub;\nexport const includesEvery = __anyStub;\nexport const isDashboardPageLayoutInEditMode = __anyStub;\nexport const isDefined = __anyStub;\nexport const isInSidePanel = __anyStub;\nexport const isLayoutCustomizationModeEnabled = __anyStub;\nexport const isNonEmptyString = __anyStub;\nexport const isSelectAll = __anyStub;\nexport const none = __anyStub;\nexport const noneDefined = __anyStub;\nexport const noneEquals = __anyStub;\nexport const numberOfSelectedRecords = __anyStub;\nexport const objectMetadataItem = __anyStub;\nexport const objectMetadataLabel = __anyStub;\nexport const objectPermissions = __anyStub;\nexport const pageType = __anyStub;\nexport const selectedRecords = __anyStub;\nexport const some = __anyStub;\nexport const someDefined = __anyStub;\nexport const someEquals = __anyStub;\nexport const someNonEmptyString = __anyStub;\nexport const targetObjectReadPermissions = __anyStub;\nexport const targetObjectWritePermissions = __anyStub;\nexport const validateFields = __anyStub;\n", "/**\n * Permanent identifiers for Greenlight's logic functions.\n *\n * Same permanence rule as `universal-identifiers.ts`: a logic function's\n * `universalIdentifier` is how Twenty recognises an existing registration across\n * upgrades. Change one and the workspace gets a *second* function registered\n * alongside the old one \u2014 for a database-event trigger that means every Person\n * event is handled twice, and every scored lead gets two audit rows. Never edit\n * a value in this file. Adding is fine.\n *\n * These live apart from `universal-identifiers.ts` purely so two workstreams can\n * add entities without fighting over the same file.\n */\n\nexport const POST_INSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =\n  'feb529fe-4048-49cd-a304-bef009952699';\n\nexport const UNINSTALL_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =\n  '4219d61c-c663-44d3-9978-758f89862ece';\n\n/**\n * Scoring is registered twice because `databaseEventTriggerSettings.eventName`\n * is a single string, not a list \u2014 see `score-person-created.logic-function.ts`\n * for why two narrow registrations beat one `person.*` wildcard.\n */\nexport const SCORE_PERSON_CREATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =\n  '03736f42-ea80-4de7-9ae1-1264cc1adad0';\n\nexport const SCORE_PERSON_UPDATED_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER =\n  'f3d817a4-806b-488a-9707-1988c58acee7';\n", "/**\n * The narrowest possible view of Twenty's Core API client.\n *\n * `CoreApiClient` from `twenty-client-sdk/core` is typed `any` until\n * `dev:generate-client` regenerates it against the installed workspace schema,\n * so depending on it directly buys no type safety and costs testability \u2014 the\n * class reads `API_URL` / `APP_ACCESS_TOKEN` from the process environment in its\n * constructor, which no unit test has.\n *\n * Everything in this folder therefore talks to `GreenlightApiClient`. The\n * `define*` files are the only place `new CoreApiClient()` appears, and they do\n * nothing but hand it to a handler that can be driven by a fake in tests.\n */\n\nexport interface GreenlightApiClient {\n  query(request: Record<string, unknown>): Promise<unknown>;\n  mutation(request: Record<string, unknown>): Promise<unknown>;\n}\n\nexport const isPlainRecord = (\n  value: unknown,\n): value is Record<string, unknown> =>\n  typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/**\n * Twenty returns connections as `{ edges: [{ node }] }`. Pull the nodes out\n * without assuming the shape is correct \u2014 a schema drift should degrade to\n * \"no records found\", never throw.\n */\nexport const readConnectionNodes = (\n  payload: unknown,\n  connectionName: string,\n): Record<string, unknown>[] => {\n  if (!isPlainRecord(payload)) {\n    return [];\n  }\n\n  const connection = payload[connectionName];\n\n  if (!isPlainRecord(connection)) {\n    return [];\n  }\n\n  const edges = connection['edges'];\n\n  if (!Array.isArray(edges)) {\n    return [];\n  }\n\n  return edges.flatMap((edge): Record<string, unknown>[] => {\n    if (!isPlainRecord(edge)) {\n      return [];\n    }\n\n    const node = edge['node'];\n\n    return isPlainRecord(node) ? [node] : [];\n  });\n};\n\n/** ISO-8601 sorts lexicographically, so this needs no Date parsing. */\nexport const oldestByCreatedAt = (\n  records: readonly Record<string, unknown>[],\n): Record<string, unknown> | null => {\n  let oldest: Record<string, unknown> | null = null;\n  let oldestKey: string | null = null;\n\n  for (const record of records) {\n    const createdAt = record['createdAt'];\n    const key = typeof createdAt === 'string' ? createdAt : '';\n\n    if (oldest === null || oldestKey === null || key < oldestKey) {\n      oldest = record;\n      oldestKey = key;\n    }\n  }\n\n  return oldest;\n};\n\n/**\n * Structured log line. Logic functions have no logger injected \u2014 stdout is what\n * `yarn twenty dev:function:logs` shows \u2014 so everything Greenlight emits is a\n * single JSON object with a stable `event` key that support can grep for.\n */\nexport const logGreenlight = (\n  event: string,\n  detail: Record<string, unknown>,\n): void => {\n  // eslint-disable-next-line no-console\n  console.log(JSON.stringify({ app: 'numaya-greenlight', event, ...detail }));\n};\n\nexport const describeError = (error: unknown): string => {\n  if (error instanceof Error) {\n    return `${error.name}: ${error.message}`;\n  }\n\n  if (typeof error === 'string') {\n    return error;\n  }\n\n  try {\n    return JSON.stringify(error) ?? 'unknown error';\n  } catch {\n    return 'unknown error';\n  }\n};\n", "/**\n * The enrichable field catalogue: what may be asked for, in what shape.\n *\n * One table, read by three consumers that must not disagree \u2014 the prompt (what\n * the model is asked), the extractor (what is accepted back) and the gap\n * analysis (what is worth asking about at all). Keeping them keyed off the same\n * array is what stops the classic drift where a field is prompted for and then\n * silently discarded, or accepted without ever being requested.\n *\n * Every entry answers a *firmographic* question. Nothing here is a contact\n * detail: see the note on `EnrichableFieldKey` for why that boundary is a hard\n * one rather than a starting point.\n */\n\nimport type {\n  EnrichableFieldKey,\n  EnrichableFieldSpec,\n} from 'src/enrichment/types';\n\nexport const ENRICHABLE_FIELD_SPECS: readonly EnrichableFieldSpec[] = [\n  {\n    key: 'industry',\n    label: 'Industry',\n    question: \"What industry does this person's employer operate in?\",\n    kind: 'text',\n    maxLength: 60,\n  },\n  {\n    key: 'region',\n    label: 'Region',\n    question: 'Which country or region is the employer headquartered in?',\n    kind: 'text',\n    maxLength: 60,\n  },\n  {\n    key: 'employeeCount',\n    label: 'Employee count',\n    question: 'Approximately how many people does the employer employ?',\n    kind: 'integer',\n    maxLength: 12,\n  },\n  {\n    key: 'jobTitle',\n    label: 'Job title',\n    question: 'What is this person\u2019s job title at that employer?',\n    kind: 'text',\n    maxLength: 120,\n  },\n  {\n    key: 'seniority',\n    label: 'Seniority',\n    question:\n      'What seniority level does that job title correspond to (for example: C-level, VP, Director, Manager, Individual contributor)?',\n    kind: 'text',\n    maxLength: 40,\n  },\n];\n\nconst SPEC_BY_KEY: ReadonlyMap<string, EnrichableFieldSpec> = new Map(\n  ENRICHABLE_FIELD_SPECS.map((spec) => [spec.key, spec]),\n);\n\nexport const findFieldSpec = (key: string): EnrichableFieldSpec | null =>\n  SPEC_BY_KEY.get(key) ?? null;\n\nexport const isEnrichableFieldKey = (key: unknown): key is EnrichableFieldKey =>\n  typeof key === 'string' && SPEC_BY_KEY.has(key);\n\n/**\n * The dotted paths a workspace adds to its Layer 3 field mapping to let the\n * deterministic scorer read enriched values.\n *\n * Published from here rather than hard-coded in the config seed because the\n * shape of the provenance blob is this module's business, and a path written out\n * by hand somewhere else is a path that goes stale the first time the blob's\n * version changes.\n *\n * The ordering is the important part: the enriched path goes **after** the\n * workspace's own candidates in every mapping, never before. `field-access.ts`\n * tries candidates in order and takes the first that yields a value, so a human\n * value always wins and enrichment only ever fills a hole. That is the same\n * promise the storage shape makes \u2014 enrichment never overwrites a person \u2014 held\n * at the read side as well as the write side.\n */\nexport const enrichedFieldMappingPath = (key: EnrichableFieldKey): string =>\n  `greenlightEnrichment.fields.${key}.parsedValue`;\n\nexport const ENRICHED_FIELD_MAPPING_PATHS: Readonly<\n  Record<EnrichableFieldKey, string>\n> = Object.freeze(\n  Object.fromEntries(\n    ENRICHABLE_FIELD_SPECS.map((spec) => [\n      spec.key,\n      enrichedFieldMappingPath(spec.key),\n    ]),\n  ) as Record<EnrichableFieldKey, string>,\n);\n", "/**\n * Numaya Greenlight \u2014 deterministic scoring engine types.\n *\n * This module is intentionally free of any Twenty SDK import, any network call,\n * any filesystem access and any clock read. Everything the engine needs arrives\n * through `scoreLead()`'s input, including `now`. That is what makes the whole\n * scoring path unit-testable in complete isolation.\n */\n\n/** Bumped whenever a change alters the score a given lead would receive. */\nexport const SCORING_ENGINE_VERSION = '0.1.0';\n\n/* -------------------------------------------------------------------------- */\n/* Lead input                                                                  */\n/* -------------------------------------------------------------------------- */\n\n/**\n * A lead as the engine sees it: an opaque bag of field values plus an optional\n * record id used only for the trace. The engine never assumes a field name \u2014\n * every read goes through the configured {@link FieldMapping}.\n */\nexport interface LeadRecord {\n  readonly id?: string | null;\n  readonly fields: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Logical field keys. Rules only ever speak in these; the customer's actual\n * column names live in the config's field mapping.\n */\nexport type LeadFieldKey =\n  | 'companyName'\n  | 'industry'\n  | 'region'\n  | 'employeeCount'\n  | 'contactName'\n  | 'jobTitle'\n  | 'seniority'\n  | 'email'\n  | 'phone'\n  | 'lastVerifiedAt'\n  /** Greenlight's own block-list flag. Its mapping is not customer-configurable. */\n  | 'suppressed'\n  /** Greenlight's own block-list reason code. Read for the explanation, not the verdict. */\n  | 'suppressionReason'\n  /** The *customer's* opt-out column(s), wherever the Layer 3 mapping points. */\n  | 'optedOut';\n\nexport const LEAD_FIELD_KEYS: readonly LeadFieldKey[] = [\n  'companyName',\n  'industry',\n  'region',\n  'employeeCount',\n  'contactName',\n  'jobTitle',\n  'seniority',\n  'email',\n  'phone',\n  'lastVerifiedAt',\n  'suppressed',\n  'suppressionReason',\n  'optedOut',\n];\n\n/**\n * One or more dotted paths into the lead record, tried in order. Multiple\n * candidates let a workspace keep a preferred field with sane fallbacks\n * (e.g. `lastVerifiedAt` \u2192 `updatedAt` \u2192 `createdAt`).\n */\nexport type FieldMapping = Readonly<\n  Record<LeadFieldKey, readonly string[]>\n>;\n\n/** What a rule actually looked at, so the trace can show its working. */\nexport interface FieldObservation {\n  readonly key: LeadFieldKey;\n  /** The candidate path that produced a value, or null when none did. */\n  readonly mappedTo: string | null;\n  readonly candidates: readonly string[];\n  readonly present: boolean;\n  /** Human-readable rendering of the value, e.g. `Manufacturing` / `(not set)`. */\n  readonly display: string;\n}\n\n/**\n * Field reader handed to every rule. All lookups are recorded so the trace\n * entry can name the exact fields consulted and the values seen.\n */\nexport interface FieldReader {\n  text(key: LeadFieldKey): string | null;\n  textList(key: LeadFieldKey): readonly string[];\n  number(key: LeadFieldKey): number | null;\n  date(key: LeadFieldKey): Date | null;\n  /** True when any mapped candidate resolves truthy; null when none are set. */\n  booleanAny(key: LeadFieldKey): boolean | null;\n  observations(): readonly FieldObservation[];\n}\n\n/* -------------------------------------------------------------------------- */\n/* Configuration                                                               */\n/* -------------------------------------------------------------------------- */\n\nexport type RuleSeverity =\n  /** A failure blocks the lead outright (compliance), whatever the score. */\n  | 'blocking'\n  /** A failure gates the lead even if the score clears the threshold. */\n  | 'critical'\n  | 'major'\n  | 'minor'\n  /** Reported in the trace but never contributes to the score. */\n  | 'advisory';\n\nexport const RULE_SEVERITIES: readonly RuleSeverity[] = [\n  'blocking',\n  'critical',\n  'major',\n  'minor',\n  'advisory',\n];\n\nexport type RuleCategory = 'icp' | 'contact' | 'data-quality' | 'compliance';\n\nexport interface IcpSizeBand {\n  readonly label: string;\n  readonly minEmployees: number;\n  /** `null` means unbounded. */\n  readonly maxEmployees: number | null;\n}\n\nexport interface IcpConfig {\n  /** Empty list means \"no opinion\" \u2014 the matching rule reports not-applicable. */\n  readonly industries: readonly string[];\n  readonly regions: readonly string[];\n  readonly sizeBands: readonly IcpSizeBand[];\n}\n\nexport interface ScoringBand {\n  readonly id: string;\n  readonly label: string;\n  /** Inclusive lower bound on the 0-100 score. */\n  readonly minScore: number;\n}\n\nexport interface RuleSetting {\n  readonly enabled: boolean;\n  readonly severity: RuleSeverity;\n  /** Relative weight. Only meaningful against the other enabled rules. */\n  readonly weight: number;\n}\n\nexport interface ResolvedScoringConfig {\n  readonly icp: IcpConfig;\n  readonly rules: Readonly<Record<string, RuleSetting>>;\n  /** Sorted high \u2192 low by `minScore`. */\n  readonly bands: readonly ScoringBand[];\n  /** Score at or above which a lead is approved. */\n  readonly gateThreshold: number;\n  readonly defaultShelfLifeDays: number;\n  readonly fieldShelfLifeDays: Readonly<Partial<Record<LeadFieldKey, number>>>;\n  /** Title keywords that indicate authority to buy. */\n  readonly decisionMakerTitles: readonly string[];\n  /** Title keywords that indicate influence but not authority (partial credit). */\n  readonly influencerTitles: readonly string[];\n  /** Mailbox local-parts that mean \"shared inbox, nobody owns replies\". */\n  readonly roleInboxLocalParts: readonly string[];\n  /** Values that mean \"somebody typed something rather than nothing\". */\n  readonly placeholderValues: readonly string[];\n  readonly fieldMapping: FieldMapping;\n}\n\n/** A deeply-optional config, i.e. whatever came out of the CRM config record. */\nexport type ScoringConfigInput = unknown;\n\n/**\n * Vocabulary that replaces the shipped defaults as the *fall-back* for a\n * workspace that has not expressed its own opinion.\n *\n * Structurally identical to the calibration baseline in `src/calibration/`, and\n * deliberately declared here rather than imported from there: the engine must\n * not be able to tell where a baseline came from, and a `src/scoring/` import of\n * `src/calibration/` would invert a dependency direction that is load-bearing\n * (see `src/calibration/index.ts`). Every field is optional \u2014 an absent one\n * leaves the corresponding shipped default exactly as it is.\n *\n * It carries no weights, no thresholds and no rule identifiers, and there is no\n * field here through which one could be smuggled. The worst a baseline can do is\n * change which strings a rule matches.\n */\nexport interface ScoringVocabularyBaseline {\n  readonly decisionMakerTitles?: readonly string[];\n  readonly influencerTitles?: readonly string[];\n  readonly roleInboxLocalParts?: readonly string[];\n  readonly placeholderValues?: readonly string[];\n  /** Canonical industry term \u2192 equivalent free-text variants. */\n  readonly industrySynonyms?: Readonly<Record<string, readonly string[]>>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Fail-open reporting                                                         */\n/* -------------------------------------------------------------------------- */\n\nexport type DegradationCode =\n  | 'config_missing'\n  | 'config_malformed'\n  | 'icp_malformed'\n  | 'rules_malformed'\n  | 'rule_setting_malformed'\n  | 'weight_malformed'\n  | 'severity_malformed'\n  | 'bands_malformed'\n  | 'gate_threshold_malformed'\n  | 'shelf_life_malformed'\n  | 'field_mapping_malformed'\n  | 'title_list_malformed'\n  | 'lead_malformed'\n  | 'now_malformed'\n  | 'rule_errored'\n  | 'no_scorable_rules'\n  | 'engine_errored';\n\n/**\n * A recorded fall-back. Every degradation means the engine chose to keep going\n * with a safe default rather than fail \u2014 the product's core promise is that a\n * lead is never lost and never silently dropped.\n */\nexport interface Degradation {\n  readonly code: DegradationCode;\n  /** Written for a CRM admin, not a developer. */\n  readonly message: string;\n  readonly detail?: string;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Rules                                                                       */\n/* -------------------------------------------------------------------------- */\n\nexport type RuleOutcome =\n  | 'pass'\n  | 'partial'\n  | 'fail'\n  /** The rule has nothing to judge (e.g. the ICP list is empty). Not scored. */\n  | 'not_applicable'\n  /** Turned off in configuration. Not scored. */\n  | 'skipped'\n  /** The rule threw. Not scored \u2014 a broken rule never drags a lead down. */\n  | 'errored';\n\nexport type RuleDetail = Readonly<\n  Record<string, string | number | boolean | null | undefined>\n>;\n\n/** What a rule returns. `credit` defaults to 1 for pass and 0 for fail. */\nexport interface RuleVerdict {\n  readonly outcome: 'pass' | 'partial' | 'fail' | 'not_applicable';\n  /** 0-1. Required for `partial`; ignored elsewhere unless supplied. */\n  readonly credit?: number;\n  /** One sentence a salesperson understands. */\n  readonly explanation: string;\n  /** What to do about it, when there is something to do. */\n  readonly remedy?: string;\n  readonly detail?: RuleDetail;\n}\n\nexport interface RuleContext {\n  readonly lead: LeadRecord;\n  readonly config: ResolvedScoringConfig;\n  /** Null when the caller supplied an unusable `now`; time-based rules opt out. */\n  readonly now: Date | null;\n  readonly read: FieldReader;\n}\n\n/**\n * A single deterministic check. Adding a rule is a local change: write one of\n * these, add it to the catalogue array, done \u2014 defaults, config plumbing,\n * weighting, tracing and fail-open handling are all inherited.\n */\nexport interface ScoringRule {\n  readonly id: string;\n  /** Short label shown in the CRM, e.g. \"Decision-maker\". */\n  readonly name: string;\n  readonly category: RuleCategory;\n  /** The question the rule answers, in the buyer's words. */\n  readonly question: string;\n  /** Why the rule exists. Published in the rule catalogue and shown in-app. */\n  readonly why: string;\n  readonly defaultEnabled: boolean;\n  readonly defaultSeverity: RuleSeverity;\n  readonly defaultWeight: number;\n  readonly reads: readonly LeadFieldKey[];\n  evaluate(context: RuleContext): RuleVerdict;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Result                                                                      */\n/* -------------------------------------------------------------------------- */\n\nexport type GateDecision =\n  /** Cleared to work. */\n  | 'approved'\n  /** Held in the greenlight queue: visible, explained, human-overridable. */\n  | 'gated'\n  /** Compliance stop (e.g. opted out). Still visible and overridable. */\n  | 'blocked'\n  /** Nothing could be scored. Fail-open: the lead passes through, flagged. */\n  | 'unscored';\n\nexport interface RuleTraceEntry {\n  readonly ruleId: string;\n  readonly ruleName: string;\n  readonly category: RuleCategory;\n  readonly question: string;\n  readonly outcome: RuleOutcome;\n  readonly severity: RuleSeverity;\n  /** 0-1 share of this rule's weight that the lead earned. */\n  readonly credit: number;\n  readonly weight: number;\n  readonly pointsEarned: number;\n  readonly pointsPossible: number;\n  /** False for skipped / not-applicable / errored / advisory rules. */\n  readonly contributed: boolean;\n  readonly explanation: string;\n  readonly remedy?: string;\n  readonly detail?: RuleDetail;\n  readonly observations: readonly FieldObservation[];\n  readonly error?: string;\n}\n\nexport interface ScoringResult {\n  /** 0-100, rounded to one decimal. Null only when nothing was scorable. */\n  readonly score: number | null;\n  readonly band: ScoringBand | null;\n  readonly decision: GateDecision;\n  readonly gateThreshold: number;\n  /** One sentence for the top of the lead record. */\n  readonly summary: string;\n  /** The headline reasons behind the decision, worst first. */\n  readonly reasons: readonly string[];\n  readonly trace: readonly RuleTraceEntry[];\n  readonly degradations: readonly Degradation[];\n  readonly configSource: ConfigSource;\n  /** ISO timestamp of the `now` that was passed in. */\n  readonly scoredAt: string | null;\n  readonly leadId: string | null;\n  readonly engineVersion: string;\n  readonly totalWeight: number;\n  readonly earnedWeight: number;\n}\n\nexport type ConfigSource = 'provided' | 'defaults' | 'repaired';\n\nexport interface ConfigResolution {\n  readonly config: ResolvedScoringConfig;\n  readonly source: ConfigSource;\n  readonly degradations: readonly Degradation[];\n}\n\nexport interface ScoreLeadInput {\n  readonly lead: LeadRecord;\n  /**\n   * The clock, passed in. The engine never reads the clock itself, so every\n   * run is reproducible from its inputs alone.\n   */\n  readonly now: Date;\n  /** Raw config record straight from the CRM. Anything unusable is repaired. */\n  readonly config?: ScoringConfigInput;\n  /** Override the rule catalogue (tests, future per-workspace rule packs). */\n  readonly rules?: readonly ScoringRule[];\n  /**\n   * Licence-delivered vocabulary, if any. Absent \u2014 which is the unlicensed,\n   * offline and signature-failing case \u2014 scores identically to a build that\n   * never had this parameter.\n   */\n  readonly baseline?: ScoringVocabularyBaseline | null;\n}\n\n/** Public documentation shape for the rule catalogue (docs + in-app help). */\nexport interface RuleCatalogueEntry {\n  readonly id: string;\n  readonly name: string;\n  readonly category: RuleCategory;\n  readonly question: string;\n  readonly why: string;\n  readonly reads: readonly LeadFieldKey[];\n  readonly defaultEnabled: boolean;\n  readonly defaultSeverity: RuleSeverity;\n  readonly defaultWeight: number;\n}\n", "/**\n * The adapter between the `GreenlightConfig` CRM record and the scoring engine.\n *\n * These are two different shapes on purpose and the gap has to live somewhere:\n *\n *   GreenlightConfig  is designed for a human with a record page. Bands are three\n *                     separate NUMBER fields because a typo inside a JSON blob\n *                     would silently gate a whole workspace; enable/severity and\n *                     weight are separate RAW_JSON maps because they are two\n *                     different decisions an admin makes at different times.\n *\n *   ResolvedScoringConfig  is designed for the engine. Bands are one sorted\n *                     array; every rule carries enabled + severity + weight\n *                     together.\n *\n * This file is the only place that knows both. Everything here is a pure\n * function of its input \u2014 no API client, no clock \u2014 so the whole\n * seed / read / merge story is unit-testable without a Twenty instance.\n */\n\nimport { buildDefaultConfig, DEFAULT_FIELD_MAPPING } from 'src/scoring';\nimport type { ResolvedScoringConfig } from 'src/scoring';\n\nimport { isPlainRecord } from 'src/logic-functions/greenlight-api';\n\n/**\n * The `GreenlightConfig.leadObjectNameSingular` SELECT value for Person.\n *\n * Duplicated from `src/objects/greenlight-config.ts` rather than imported: that\n * module pulls in `twenty-sdk/define`, and a logic-function bundle has no\n * business carrying the whole manifest-authoring toolkit. The value is a SELECT\n * option and is as permanent as the field identifier itself.\n */\nexport const DEFAULT_LEAD_OBJECT_SELECT_VALUE = 'PERSON';\n\n/** Lowercase API name matching the SELECT value above, for the audit trail. */\nexport const LEAD_OBJECT_SELECT_TO_NAME_SINGULAR: Readonly<\n  Record<string, string>\n> = {\n  PERSON: 'person',\n  COMPANY: 'company',\n  OPPORTUNITY: 'opportunity',\n};\n\n/** Every field this app reads from or writes to the config record. */\nexport const GREENLIGHT_CONFIG_FIELD_NAMES = [\n  'id',\n  'createdAt',\n  'name',\n  'isGateEnabled',\n  'icpIndustries',\n  'icpRegions',\n  'icpSizeBands',\n  'ruleSettings',\n  'scoreWeights',\n  'bandExcellentThreshold',\n  'bandGoodThreshold',\n  'bandFairThreshold',\n  'gateThreshold',\n  'defaultShelfLifeDays',\n  'fieldShelfLives',\n  'leadObjectNameSingular',\n  'decisionMakerFieldName',\n  'decisionMakerMatchValues',\n  'readyForOutreachFieldName',\n  'readyForOutreachValue',\n  'optOutFieldNames',\n] as const;\n\n/** GraphQL selection set for the fields above. */\nexport const greenlightConfigSelection = (): Record<string, boolean> =>\n  Object.fromEntries(GREENLIGHT_CONFIG_FIELD_NAMES.map((name) => [name, true]));\n\nexport type GreenlightConfigSeed = Record<string, unknown>;\n\nconst bandMinScore = (\n  config: ResolvedScoringConfig,\n  bandId: string,\n): number | undefined =>\n  config.bands.find((band) => band.id === bandId)?.minScore;\n\n/**\n * The record the post-install hook writes on a fresh install.\n *\n * Every value is set **explicitly** rather than left to the field manifest's\n * `defaultValue`, for three reasons:\n *\n *  1. The manifest defaults and the engine defaults disagree. The field\n *     manifests carry bands 80/60/40 and gate 40; `buildDefaultConfig()` \u2014 the\n *     thing that actually scores leads \u2014 carries 85/70/50 and gate 50. Whichever\n *     is \"right\", they must not differ, and the engine is the one that decides\n *     outcomes, so the engine wins. Leaving the record blank would ship a\n *     workspace whose visible configuration lies about its own behaviour.\n *     `decisionMakerMatchValues` has the same problem: 12 titles in the manifest,\n *     25 in the engine.\n *  2. `ruleSettings` and `scoreWeights` cannot come from a manifest default at\n *     all \u2014 they are keyed by the rule catalogue, which the engine owns and which\n *     grows every release.\n *  3. A `defaultValue` only applies at column creation. It is not a value a\n *     later read can distinguish from \"the admin set it to that\", so relying on\n *     it would make the upgrade-merge below unable to tell missing from chosen.\n *\n * The rule of thumb: if the engine has an opinion, seed it explicitly; the field\n * manifest `defaultValue` is then only a safety net for records created by hand.\n */\nexport const buildGreenlightConfigSeed = (): GreenlightConfigSeed => {\n  const defaults = buildDefaultConfig();\n\n  const ruleSettings: Record<string, { enabled: boolean; severity: string }> =\n    {};\n  const scoreWeights: Record<string, number> = {};\n\n  for (const [ruleId, setting] of Object.entries(defaults.rules)) {\n    ruleSettings[ruleId] = {\n      enabled: setting.enabled,\n      severity: setting.severity,\n    };\n    scoreWeights[ruleId] = setting.weight;\n  }\n\n  return {\n    name: 'Default',\n    isGateEnabled: true,\n\n    icpIndustries: [...defaults.icp.industries],\n    icpRegions: [...defaults.icp.regions],\n    icpSizeBands: { bands: [...defaults.icp.sizeBands] },\n\n    ruleSettings,\n    scoreWeights,\n\n    bandExcellentThreshold: bandMinScore(defaults, 'excellent') ?? 85,\n    bandGoodThreshold: bandMinScore(defaults, 'good') ?? 70,\n    bandFairThreshold: bandMinScore(defaults, 'fair') ?? 50,\n    gateThreshold: defaults.gateThreshold,\n\n    defaultShelfLifeDays: defaults.defaultShelfLifeDays,\n    fieldShelfLives: { ...defaults.fieldShelfLifeDays },\n\n    leadObjectNameSingular: DEFAULT_LEAD_OBJECT_SELECT_VALUE,\n    decisionMakerFieldName: 'jobTitle',\n    decisionMakerMatchValues: [...defaults.decisionMakerTitles],\n\n    // Stock Twenty's Person has no stage field, so there is nothing honest to\n    // point these at. Blank means \"the release action only clears the gate\".\n    readyForOutreachFieldName: null,\n    readyForOutreachValue: null,\n\n    // Empty, not absent: the engine's default field mapping already probes\n    // `optedOut` / `doNotContact` / `emailOptOut` / `unsubscribed`. This list is\n    // for *extra* workspace-specific opt-out fields.\n    optOutFieldNames: [],\n  };\n};\n\n/* -------------------------------------------------------------------------- */\n/* Upgrade merge                                                               */\n/* -------------------------------------------------------------------------- */\n\nconst isMissing = (value: unknown): boolean =>\n  value === undefined || value === null;\n\n/**\n * Whether writing `seedValue` over a missing field would actually change\n * anything once Twenty has stored it.\n *\n * Found by running a real `app:install` upgrade rather than by a unit test, and\n * unit tests structurally cannot see it: **Twenty persists an empty `RAW_JSON`\n * as `null`.** So `fieldShelfLives`, seeded `{}`, reads back as `null`,\n * `isMissing` says missing, the patch writes `{}` again, and it reads back\n * `null` again \u2014 forever. Every single upgrade patched exactly one key and filed\n * an audit row claiming a merge that had not happened, which quietly makes the\n * upgrade trail untrustworthy for the merges that are real.\n *\n * A patch that cannot converge is not a merge, it is a loop with an audit trail.\n * An empty seed value written over a missing field is a no-op by definition, so\n * it is skipped and the key is left to the field manifest's own default.\n */\nconst isNoOpSeed = (value: unknown): boolean => {\n  if (Array.isArray(value)) {\n    return value.length === 0;\n  }\n\n  if (isPlainRecord(value)) {\n    return Object.keys(value).length === 0;\n  }\n\n  return false;\n};\n\n/**\n * The patch an upgrade should apply to an existing config record.\n *\n * \"Missing\" means `null` or `undefined` only. An empty array, an empty object\n * and a zero are all *choices* a workspace made \u2014 a permissive ICP is the whole\n * point of the shipped default \u2014 and resetting them to seed values would be the\n * exact behaviour ARCHITECTURE.md's upgrade section forbids (\"config merge, not\n * replace\").\n *\n * The interesting case is `ruleSettings` / `scoreWeights`: a release that adds a\n * rule must make that rule appear in the workspace's config at its shipped\n * default, without disturbing a single existing entry. Both maps are therefore\n * merged key-by-key rather than compared wholesale.\n *\n * Returns an empty object when there is nothing to do, so the caller can skip\n * the mutation entirely \u2014 which is what makes re-running the hook a no-op.\n */\nexport const buildConfigUpgradePatch = (\n  existing: unknown,\n  seed: GreenlightConfigSeed = buildGreenlightConfigSeed(),\n): Record<string, unknown> => {\n  const record = isPlainRecord(existing) ? existing : {};\n  const patch: Record<string, unknown> = {};\n\n  for (const [key, seedValue] of Object.entries(seed)) {\n    // `null` is the intended seeded value for these two, so a null on the\n    // record is indistinguishable from the seed and must never be \"repaired\".\n    if (seedValue === null) {\n      continue;\n    }\n\n    if (key === 'ruleSettings' || key === 'scoreWeights') {\n      continue;\n    }\n\n    if (isMissing(record[key]) && !isNoOpSeed(seedValue)) {\n      patch[key] = seedValue;\n    }\n  }\n\n  const ruleSettingsPatch = mergeKeyedMap(\n    record['ruleSettings'],\n    seed['ruleSettings'],\n  );\n\n  if (ruleSettingsPatch !== null) {\n    patch['ruleSettings'] = ruleSettingsPatch;\n  }\n\n  const scoreWeightsPatch = mergeKeyedMap(\n    record['scoreWeights'],\n    seed['scoreWeights'],\n  );\n\n  if (scoreWeightsPatch !== null) {\n    patch['scoreWeights'] = scoreWeightsPatch;\n  }\n\n  return patch;\n};\n\n/**\n * Merge shipped keys into a stored map without overwriting anything present.\n * Returns `null` when the stored map already covers every shipped key \u2014 the\n * signal that no write is needed.\n */\nconst mergeKeyedMap = (\n  stored: unknown,\n  shipped: unknown,\n): Record<string, unknown> | null => {\n  if (!isPlainRecord(shipped)) {\n    return null;\n  }\n\n  if (!isPlainRecord(stored)) {\n    // Absent or unreadable: replacing it with the shipped map loses nothing,\n    // because there was nothing legible there to lose.\n    return { ...shipped };\n  }\n\n  const merged: Record<string, unknown> = { ...stored };\n  let added = false;\n\n  for (const [key, value] of Object.entries(shipped)) {\n    if (isMissing(merged[key])) {\n      merged[key] = value;\n      added = true;\n    }\n  }\n\n  return added ? merged : null;\n};\n\n/* -------------------------------------------------------------------------- */\n/* Record -> engine config                                                     */\n/* -------------------------------------------------------------------------- */\n\nconst asFiniteNumber = (value: unknown): number | undefined =>\n  typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n\nconst asStringList = (value: unknown): string[] | undefined => {\n  if (!Array.isArray(value)) {\n    return undefined;\n  }\n\n  const list = value\n    .filter((entry): entry is string => typeof entry === 'string')\n    .map((entry) => entry.trim())\n    .filter((entry) => entry.length > 0);\n\n  return list;\n};\n\n/** `icpSizeBands` ships as `{ bands: [...] }`; tolerate a bare array too. */\nconst readSizeBands = (value: unknown): unknown => {\n  if (Array.isArray(value)) {\n    return value;\n  }\n\n  if (isPlainRecord(value) && Array.isArray(value['bands'])) {\n    return value['bands'];\n  }\n\n  return undefined;\n};\n\n/**\n * Recombine `ruleSettings` (enable + severity) and `scoreWeights` (weight) into\n * the single per-rule shape the engine reads.\n *\n * `isEnabled` is accepted as an alias for `enabled` because the field's own\n * description in `src/objects/greenlight-config.ts` documents that spelling.\n * The engine reads `enabled`; rather than let a hand-edited record silently do\n * nothing, both are honoured here. (The field description is stale \u2014 see the\n * report accompanying this change.)\n */\nconst readRules = (\n  ruleSettings: unknown,\n  scoreWeights: unknown,\n): Record<string, unknown> | undefined => {\n  const settings = isPlainRecord(ruleSettings) ? ruleSettings : undefined;\n  const weights = isPlainRecord(scoreWeights) ? scoreWeights : undefined;\n\n  if (settings === undefined && weights === undefined) {\n    return undefined;\n  }\n\n  const ruleIds = new Set<string>([\n    ...Object.keys(settings ?? {}),\n    ...Object.keys(weights ?? {}),\n  ]);\n\n  const rules: Record<string, unknown> = {};\n\n  for (const ruleId of ruleIds) {\n    const setting = settings?.[ruleId];\n    const merged: Record<string, unknown> = isPlainRecord(setting)\n      ? { ...setting }\n      : {};\n\n    if (merged['enabled'] === undefined && merged['isEnabled'] !== undefined) {\n      merged['enabled'] = merged['isEnabled'];\n    }\n\n    const weight = asFiniteNumber(weights?.[ruleId]);\n\n    if (weight !== undefined) {\n      merged['weight'] = weight;\n    }\n\n    rules[ruleId] = merged;\n  }\n\n  return rules;\n};\n\n/**\n * Rebuild the engine's band array from the three threshold fields.\n *\n * Returns `undefined` when no threshold is usable, which makes `resolveConfig`\n * fall back to the shipped bands without logging a degradation \u2014 the right\n * outcome, because \"the admin never touched this\" is not a fault.\n */\nconst readBands = (record: Record<string, unknown>): unknown => {\n  const excellent = asFiniteNumber(record['bandExcellentThreshold']);\n  const good = asFiniteNumber(record['bandGoodThreshold']);\n  const fair = asFiniteNumber(record['bandFairThreshold']);\n\n  if (excellent === undefined && good === undefined && fair === undefined) {\n    return undefined;\n  }\n\n  const bands: { id: string; label: string; minScore: number }[] = [];\n\n  if (excellent !== undefined) {\n    bands.push({ id: 'excellent', label: 'Excellent', minScore: excellent });\n  }\n\n  if (good !== undefined) {\n    bands.push({ id: 'good', label: 'Good', minScore: good });\n  }\n\n  if (fair !== undefined) {\n    bands.push({ id: 'fair', label: 'Fair', minScore: fair });\n  }\n\n  // Poor is the floor and has no threshold field: it is whatever is left.\n  bands.push({ id: 'poor', label: 'Poor', minScore: 0 });\n\n  return bands;\n};\n\n/**\n * The Layer 3 field mapping, expressed as *additional* candidate paths in front\n * of the engine's defaults rather than as a replacement.\n *\n * Prepending matters: a workspace that points `decisionMakerFieldName` at a\n * custom field still wants `jobTitle` probed as a fallback for the Person\n * records where the custom field is blank. De-duplicated so that pointing the\n * setting at the default field name produces the default list unchanged rather\n * than a list that probes the same path twice.\n */\nconst prepend = (\n  extra: readonly string[],\n  defaults: readonly string[],\n): string[] => [...new Set([...extra, ...defaults])];\n\nconst readFieldMapping = (\n  record: Record<string, unknown>,\n): Record<string, string[]> | undefined => {\n  const mapping: Record<string, string[]> = {};\n\n  const decisionMakerField = record['decisionMakerFieldName'];\n\n  if (typeof decisionMakerField === 'string' && decisionMakerField.trim()) {\n    // Read the shipped candidates rather than repeating them. They were\n    // duplicated here, and the two copies drifted the moment `position` was\n    // removed from the engine's list for reading Twenty's row-ordering number\n    // as a job title \u2014 this copy would have quietly kept the bug alive for any\n    // workspace that had configured a decision-maker field.\n    mapping['jobTitle'] = prepend(\n      [decisionMakerField.trim()],\n      DEFAULT_FIELD_MAPPING.jobTitle,\n    );\n  }\n\n  const optOutFields = asStringList(record['optOutFieldNames']);\n\n  if (optOutFields !== undefined && optOutFields.length > 0) {\n    mapping['optedOut'] = prepend(optOutFields, [\n      'optedOut',\n      'doNotContact',\n      'emailOptOut',\n      'unsubscribed',\n    ]);\n  }\n\n  return Object.keys(mapping).length > 0 ? mapping : undefined;\n};\n\n/**\n * Turn a `GreenlightConfig` record into the raw config `scoreLead` accepts.\n *\n * Deliberately lenient: anything unreadable is left out of the returned object\n * so `resolveConfig` supplies its own default. This function never throws and\n * never validates \u2014 validation is the engine's job and it already reports what\n * it had to repair.\n */\nexport const toScoringConfigInput = (record: unknown): unknown => {\n  if (!isPlainRecord(record)) {\n    return undefined;\n  }\n\n  const industries = asStringList(record['icpIndustries']);\n  const regions = asStringList(record['icpRegions']);\n  const sizeBands = readSizeBands(record['icpSizeBands']);\n\n  const icp =\n    industries !== undefined || regions !== undefined || sizeBands !== undefined\n      ? {\n          industries: industries ?? [],\n          regions: regions ?? [],\n          sizeBands: sizeBands ?? [],\n        }\n      : undefined;\n\n  const decisionMakerTitles = asStringList(record['decisionMakerMatchValues']);\n\n  return {\n    icp,\n    rules: readRules(record['ruleSettings'], record['scoreWeights']),\n    bands: readBands(record),\n    gateThreshold: asFiniteNumber(record['gateThreshold']),\n    defaultShelfLifeDays: asFiniteNumber(record['defaultShelfLifeDays']),\n    fieldShelfLifeDays: isPlainRecord(record['fieldShelfLives'])\n      ? record['fieldShelfLives']\n      : undefined,\n    // Empty means \"the admin cleared the list\", which disables the\n    // decision-maker rule on purpose. Only an unreadable value falls back.\n    decisionMakerTitles,\n    fieldMapping: readFieldMapping(record),\n  };\n};\n\n/** Is the gate switched on? Absent or unreadable reads as on. */\nexport const isGateEnabled = (record: unknown): boolean =>\n  !(isPlainRecord(record) && record['isGateEnabled'] === false);\n\n/** Which object the workspace calls the lead, as a lowercase API name. */\nexport const readLeadObjectNameSingular = (record: unknown): string => {\n  const raw = isPlainRecord(record) ? record['leadObjectNameSingular'] : null;\n\n  if (typeof raw !== 'string' || raw.trim().length === 0) {\n    return LEAD_OBJECT_SELECT_TO_NAME_SINGULAR[\n      DEFAULT_LEAD_OBJECT_SELECT_VALUE\n    ] as string;\n  }\n\n  const normalised = raw.trim().toUpperCase();\n\n  return LEAD_OBJECT_SELECT_TO_NAME_SINGULAR[normalised] ?? raw.trim();\n};\n", "/**\n * Install-lifecycle behaviour, separated from the `define*` wrappers so it can\n * be driven by a fake API client in unit tests.\n *\n * Twenty runs the post-install hook on a fresh install and \u2014 because this app\n * sets `shouldRunOnVersionUpgrade: true` \u2014 on every upgrade, asynchronously,\n * with up to three retries. Both facts make idempotency mandatory rather than\n * merely tidy: a retried run must create nothing new, and an upgrade must not\n * flatten a workspace's tuning back to shipped defaults.\n */\n\nimport {\n  describeError,\n  logGreenlight,\n  oldestByCreatedAt,\n  readConnectionNodes,\n  type GreenlightApiClient,\n} from 'src/logic-functions/greenlight-api';\nimport {\n  buildConfigUpgradePatch,\n  buildGreenlightConfigSeed,\n  greenlightConfigSelection,\n} from 'src/logic-functions/greenlight-config-record';\nimport { SCORING_ENGINE_VERSION } from 'src/scoring';\n\nexport interface InstallRunInput {\n  readonly client: GreenlightApiClient;\n  readonly payload: { previousVersion?: string; newVersion?: string };\n}\n\nexport type PostInstallOutcome =\n  | { status: 'seeded'; configId: string | null }\n  | { status: 'already_seeded'; configCount: number }\n  | { status: 'up_to_date'; configId: string | null }\n  | { status: 'merged'; configId: string | null; mergedKeys: string[] };\n\nconst loadConfigRecords = async (\n  client: GreenlightApiClient,\n): Promise<Record<string, unknown>[]> => {\n  const response = await client.query({\n    greenlightConfigs: { edges: { node: greenlightConfigSelection() } },\n  });\n\n  return readConnectionNodes(response, 'greenlightConfigs');\n};\n\nconst readCreatedId = (response: unknown, mutationName: string): string | null => {\n  if (typeof response !== 'object' || response === null) {\n    return null;\n  }\n\n  const created = (response as Record<string, unknown>)[mutationName];\n\n  if (typeof created !== 'object' || created === null) {\n    return null;\n  }\n\n  const id = (created as Record<string, unknown>)['id'];\n\n  return typeof id === 'string' ? id : null;\n};\n\n/**\n * Best-effort provenance row. Not worth failing an install over, so every\n * failure is swallowed after being logged \u2014 but genuinely worth having, because\n * \"when was this workspace seeded, and from which version\" is the first question\n * every support conversation about a mis-scored lead starts with.\n */\nconst writeConfigAuditRow = async (\n  client: GreenlightApiClient,\n  summary: string,\n  detail: Record<string, unknown>,\n): Promise<void> => {\n  try {\n    await client.mutation({\n      createGreenlightAuditLog: {\n        __args: {\n          data: {\n            name: summary,\n            eventType: 'CONFIG_CHANGED',\n            occurredAt: new Date().toISOString(),\n            leadObjectNameSingular: '',\n            leadDisplayName: '',\n            actorType: 'SYSTEM',\n            actorDisplayName: `Greenlight engine ${SCORING_ENGINE_VERSION}`,\n            ruleTrace: detail,\n            score: null,\n            band: 'UNSCORED',\n            decision: 'UNSCORED',\n            overrideReason: '',\n            traceId: '',\n          },\n        },\n        id: true,\n      },\n    });\n  } catch (error) {\n    logGreenlight('install_audit_write_failed', { error: describeError(error) });\n  }\n};\n\n/**\n * Seed on a fresh install; merge newly-shipped keys on an upgrade.\n *\n * ## Idempotency\n *\n * The only creation happens when the workspace has **zero** config records. A\n * retry of a run whose create already succeeded sees one record and takes the\n * \"already seeded\" branch. There is no unique constraint available on a Twenty\n * object, so a create whose response was lost in flight could in principle\n * produce a second record on retry; that duplicate is inert, because every\n * reader in this app resolves the config by `oldestByCreatedAt`, and the\n * upgrade path patches that same oldest record. Duplicate-tolerant beats\n * duplicate-impossible when the platform offers no way to be the latter.\n *\n * ## Upgrade\n *\n * `previousVersion` is `undefined` on a fresh install and set on an upgrade \u2014\n * this is the branch the ARCHITECTURE doc asks for. On an upgrade the seed is\n * never written wholesale; `buildConfigUpgradePatch` returns only the keys the\n * record is genuinely missing plus any rules the new release added, so a\n * workspace's thresholds, ICP and per-rule severities survive untouched. An\n * upgrade that adds nothing produces no mutation at all.\n *\n * ## Errors\n *\n * Deliberately **not** caught. Post-install runs async with three retries, so a\n * transient API failure should propagate and be retried by the platform \u2014\n * swallowing it would turn a recoverable blip into a permanently unseeded\n * workspace. This is safe precisely because the run is idempotent. Nothing here\n * touches lead data, so a failed seed degrades to \"the engine scores with its\n * built-in defaults\", which is the documented fall-back anyway.\n */\nexport const runPostInstall = async ({\n  client,\n  payload,\n}: InstallRunInput): Promise<PostInstallOutcome> => {\n  const existing = await loadConfigRecords(client);\n\n  if (existing.length === 0) {\n    const seed = buildGreenlightConfigSeed();\n\n    const response = await client.mutation({\n      createGreenlightConfig: { __args: { data: seed }, id: true },\n    });\n\n    const configId = readCreatedId(response, 'createGreenlightConfig');\n\n    logGreenlight('config_seeded', {\n      configId,\n      newVersion: payload.newVersion ?? null,\n    });\n\n    await writeConfigAuditRow(\n      client,\n      `CONFIG_CHANGED \u00B7 Greenlight configuration seeded \u00B7 ${payload.newVersion ?? 'unknown version'}`,\n      {\n        action: 'seeded',\n        newVersion: payload.newVersion ?? null,\n        engineVersion: SCORING_ENGINE_VERSION,\n        ruleCount: Object.keys(\n          (seed['ruleSettings'] as Record<string, unknown>) ?? {},\n        ).length,\n      },\n    );\n\n    return { status: 'seeded', configId };\n  }\n\n  const target = oldestByCreatedAt(existing);\n  const configId =\n    target !== null && typeof target['id'] === 'string' ? target['id'] : null;\n\n  if (payload.previousVersion === undefined) {\n    // Fresh install, but a record already exists: this is a retry of a run whose\n    // create landed. Do nothing at all \u2014 in particular, do not \"top up\" missing\n    // keys, because on a fresh install there are none to top up and any\n    // difference is something the admin did in the window since.\n    logGreenlight('config_seed_skipped', {\n      configCount: existing.length,\n      reason: 'config_already_present',\n    });\n\n    return { status: 'already_seeded', configCount: existing.length };\n  }\n\n  const patch = buildConfigUpgradePatch(target);\n  const mergedKeys = Object.keys(patch);\n\n  if (mergedKeys.length === 0 || configId === null) {\n    logGreenlight('config_upgrade_noop', {\n      configId,\n      previousVersion: payload.previousVersion,\n      newVersion: payload.newVersion ?? null,\n    });\n\n    return { status: 'up_to_date', configId };\n  }\n\n  await client.mutation({\n    updateGreenlightConfig: { __args: { id: configId, data: patch }, id: true },\n  });\n\n  logGreenlight('config_upgraded', {\n    configId,\n    previousVersion: payload.previousVersion,\n    newVersion: payload.newVersion ?? null,\n    mergedKeys,\n  });\n\n  await writeConfigAuditRow(\n    client,\n    `CONFIG_CHANGED \u00B7 Greenlight configuration merged on upgrade \u00B7 ${payload.newVersion ?? 'unknown version'}`,\n    {\n      action: 'merged',\n      previousVersion: payload.previousVersion,\n      newVersion: payload.newVersion ?? null,\n      mergedKeys,\n    },\n  );\n\n  return { status: 'merged', configId, mergedKeys };\n};\n\n/* -------------------------------------------------------------------------- */\n/* Uninstall                                                                   */\n/* -------------------------------------------------------------------------- */\n\nexport interface UninstallRunOutcome {\n  readonly version: string | null;\n  readonly configRecordsObserved: number;\n  readonly cleanupPerformed: 'none';\n}\n\n/**\n * Record what is about to disappear. That is genuinely all this hook can do \u2014\n * see `uninstall.logic-function.ts` for the full argument.\n *\n * Never throws: a cleanup hook that can fail an uninstall makes an app\n * impossible to remove, and the platform documents the hook as best-effort for\n * exactly that reason.\n */\nexport const runUninstall = async ({\n  client,\n  payload,\n}: {\n  client: GreenlightApiClient;\n  payload: { version?: string };\n}): Promise<UninstallRunOutcome> => {\n  let configRecordsObserved = 0;\n\n  try {\n    configRecordsObserved = (await loadConfigRecords(client)).length;\n  } catch (error) {\n    logGreenlight('uninstall_inventory_failed', {\n      error: describeError(error),\n    });\n  }\n\n  logGreenlight('uninstalled', {\n    version: payload.version ?? null,\n    engineVersion: SCORING_ENGINE_VERSION,\n    configRecordsObserved,\n    // Stated explicitly so the log is self-documenting a year from now.\n    note: 'Greenlight v0.1 provisions no external resources; the platform removes all app-owned metadata and records.',\n  });\n\n  return {\n    version: payload.version ?? null,\n    configRecordsObserved,\n    cleanupPerformed: 'none',\n  };\n};\n"],
  "mappings": "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",
  "names": []
}
