const CHECKER_CODES_TEXT = `
CHK_MSG_GEN_050
CHK_MSG_OBJ_GEN_000
CHK_MSG_OBJ_GEN_002
CHK_MSG_OBJ_GEN_004
CHK_MSG_OBJ_GEN_005
CHK_MSG_OBJ_GEN_050
CHK_MSG_OBJ_GEN_051
CHK_MSG_OBJ_GEN_052
CHK_MSG_OBJ_GEN_100
CHK_MSG_OBJ_GEN_102
CHK_MSG_OBJ_GEN_104
CHK_MSG_OBJ_GEN_105
CHK_MSG_OBJ_GEN_106
CHK_MSG_OBJ_GEN_110
CHK_MSG_OBJ_GEN_112
CHK_MSG_OBJ_GEN_114
CHK_MSG_OBJ_GEN_116
CHK_MSG_OBJ_GEN_120
CHK_MSG_OBJ_GEN_122
CHK_MSG_OBJ_GEN_200
CHK_MSG_OBJ_GEN_202
CHK_MSG_OBJ_GEN_204
CHK_MSG_OBJ_GEN_206
CHK_MSG_OBJ_GEN_208
CHK_MSG_OBJ_GEN_210
CHK_MSG_OBJ_GEN_212
CHK_MSG_OBJ_GEN_214
CHK_MSG_OBJ_GEN_216
CHK_MSG_OBJ_GEN_302
CHK_MSG_OBJ_GEN_304
CHK_MSG_OBJ_GEN_306
CHK_MSG_OBJ_GEN_308
CHK_MSG_OBJ_GEN_310
CHK_MSG_OBJ_GEN_312
CHK_MSG_OBJ_GEN_402
CHK_MSG_OBJ_GEN_404
CHK_MSG_OBJ_GEN_406
CHK_MSG_OBJ_GEN_408
CHK_MSG_OBJ_GEN_410
CHK_MSG_OBJ_GEN_412
CHK_MSG_OBJ_GEN_4120
CHK_MSG_OBJ_GEN_4121
CHK_MSG_OBJ_GEN_414
CHK_MSG_OBJ_GEN_415
CHK_MSG_OBJ_GEN_416
CHK_MSG_OBJ_GEN_418
CHK_MSG_OBJ_GEN_419
CHK_MSG_OBJ_GEN_502
CHK_MSG_OBJ_GEN_504
CHK_MSG_OBJ_GEN_506
CHK_MSG_OBJ_GEN_508
CHK_MSG_OBJ_GEN_510
CHK_MSG_OBJ_GEN_512
CHK_MSG_OBJ_GEN_514
CHK_MSG_OBJ_GEN_516
CHK_MSG_OBJ_GEN_518
CHK_MSG_OBJ_GEN_522
CHK_MSG_OBJ_GEN_602
CHK_MSG_OBJ_GEN_604
CHK_MSG_OBJ_GEN_702
CHK_MSG_OBJ_GEN_704
CHK_MSG_OBJ_GEN_705
CHK_MSG_OBJ_GEN_706
CHK_MSG_OBJ_GEN_707
CHK_MSG_OBJ_GEN_708
CHK_MSG_OBJ_GEN_710
CHK_MSG_OBJ_GEN_712
CHK_MSG_OBJ_GEN_713
CHK_MSG_OBJ_GEN_714
CHK_MSG_OBJ_GEN_850
CHK_MSG_OBJ_GEN_852
CHK_MSG_OBJ_GEN_854
CHK_MSG_OBJ_GEN_856
CHK_MSG_OBJ_GEN_858
CHK_MSG_OBJ_GEN_860
CHK_MSG_PRG_AGN_010
CHK_MSG_PRG_AGN_020
CHK_MSG_PRG_AGN_030
CHK_MSG_PRG_AGN_040
CHK_MSG_PRG_AGN_100
CHK_MSG_PRG_AGN_110
CHK_MSG_PRG_AGN_120
CHK_MSG_PRG_AGN_130
CHK_MSG_PRG_AGN_200
CHK_MSG_PRG_AGN_210
CHK_MSG_PRG_AGN_220
CHK_MSG_PRG_AGN_310
CHK_MSG_PRG_AGN_320
CHK_MSG_PRG_AGN_410
CHK_MSG_PRG_AGN_510
CHK_MSG_PRG_AGN_520
CHK_MSG_PRG_ART_010
CHK_MSG_PRG_ART_020
CHK_MSG_PRG_ART_030
CHK_MSG_PRG_ART_032
CHK_MSG_PRG_ART_042
CHK_MSG_PRG_ART_050
CHK_MSG_PRG_COM_010
CHK_MSG_PRG_COM_020
CHK_MSG_PRG_COM_030
CHK_MSG_PRG_COM_040
CHK_MSG_PRG_COM_042
CHK_MSG_PRG_COM_050
CHK_MSG_PRG_COM_052
CHK_MSG_PRG_COM_054
CHK_MSG_PRG_COM_056
CHK_MSG_PRG_DSC_010
CHK_MSG_PRG_DSC_030
CHK_MSG_PRG_DSC_032
CHK_MSG_PRG_DSC_034
CHK_MSG_PRG_DSC_040
CHK_MSG_PRG_DSC_042
CHK_MSG_PRG_DSC_200
CHK_MSG_PRG_DSC_210
CHK_MSG_PRG_DSC_220
CHK_MSG_PRG_DSC_230
CHK_MSG_PRG_EVT_010
CHK_MSG_PRG_EVT_018
CHK_MSG_PRG_EVT_020
CHK_MSG_PRG_EVT_022
CHK_MSG_PRG_EVT_030
CHK_MSG_PRG_EVT_035
CHK_MSG_PRG_EVT_102
CHK_MSG_PRG_EVT_112
CHK_MSG_PRG_EXP_012
CHK_MSG_PRG_EXP_022
CHK_MSG_PRG_EXP_024
CHK_MSG_PRG_EXP_026
CHK_MSG_PRG_EXP_028
CHK_MSG_PRG_FLD_010
CHK_MSG_PRG_FLD_012
CHK_MSG_PRG_FLD_020
CHK_MSG_PRG_FLD_022
CHK_MSG_PRG_FLD_030
CHK_MSG_PRG_FLD_040
CHK_MSG_PRG_FLD_060
CHK_MSG_PRG_FLD_070
CHK_MSG_PRG_FLD_130
CHK_MSG_PRG_FLD_160
CHK_MSG_PRG_FLD_200
CHK_MSG_PRG_FLD_210
CHK_MSG_PRG_FLD_220
CHK_MSG_PRG_FLD_300
CHK_MSG_PRG_FLD_310
CHK_MSG_PRG_FLD_320
CHK_MSG_PRG_GUI_010
CHK_MSG_PRG_GUI_020
CHK_MSG_PRG_GUI_200
CHK_MSG_PRG_GUI_250
CHK_MSG_PRG_GUI_260
CHK_MSG_PRG_GUI_262
CHK_MSG_PRG_GUI_264
CHK_MSG_PRG_GUI_266
CHK_MSG_PRG_GUI_268
CHK_MSG_PRG_JVS_012
CHK_MSG_PRG_PRM_010
CHK_MSG_PRG_PRM_020
CHK_MSG_PRG_PRM_022
CHK_MSG_PRG_PRM_030
CHK_MSG_PRG_PRM_040
CHK_MSG_PRG_PRM_050
CHK_MSG_PRG_PRM_080
CHK_MSG_PRG_PRM_090
CHK_MSG_PRG_PRM_100
CHK_MSG_PRG_TRG_008
CHK_MSG_PRG_TRG_020
CHK_MSG_PRG_TRG_040
CHK_MSG_PRG_TRG_050
CHK_MSG_PRG_TRG_060
CHK_MSG_PRG_TRG_100
CHK_MSG_PRG_TRG_110
CHK_MSG_PRG_TRG_120
CHK_MSG_PRG_TRG_130
CHK_MSG_PRG_TRG_310
CHK_MSG_PRG_TRG_320
CHK_MSG_PRG_TRG_330
CHK_MSG_PRG_TRG_334
CHK_MSG_PRG_TRG_370
CHK_MSG_PRG_TRG_372
CHK_MSG_PRG_TRG_374
CHK_MSG_PRG_TRG_380
CHK_MSG_PRG_TRG_382
CHK_MSG_PRG_TRG_384
CHK_MSG_PRG_TRG_386
CHK_MSG_PRG_TRG_388
CHK_MSG_PRG_TRG_389
CHK_MSG_PRG_TRG_400
CHK_MSG_PRG_TRG_510
CHK_MSG_PRG_TRG_512
CHK_MSG_PRG_TRG_514
CHK_MSG_PRG_TRG_516
CHK_MSG_PRG_TRG_520
CHK_MSG_PRG_TRG_610
CHK_MSG_PRG_TRG_612
CHK_MSG_PRG_TRG_614
CHK_MSG_PRG_TRG_616
CHK_MSG_PRG_TRG_618
CHK_MSG_PRG_TRG_800
CHK_MSG_PRG_TRG_810
CHK_MSG_PRG_TRG_820
CHK_MSG_PRG_TRG_900
CHK_MSG_RTE_MNU_010
CHK_MSG_RTE_MNU_020
CHK_MSG_RTE_MNU_030
CHK_MSG_TBL_FLD_012
CHK_MSG_TBL_FLD_020
CHK_MSG_TBL_FLD_022
CHK_MSG_TBL_FLD_090
CHK_MSG_TBL_FLD_100
CHK_MSG_TBL_FLD_200
CHK_MSG_TBL_GEN_0020
CHK_MSG_TBL_GEN_010
CHK_MSG_TBL_GEN_030
CHK_MSG_TBL_IDX_040
CHK_MSG_TBL_IDX_050
CHK_MSG_TBL_IDX_060
CHK_MSG_TBL_IDX_070
CHK_MSG_TBL_IDX_080
CHK_MSG_GEN_900
CHK_MSG_GEN_902
`.trim();

export const KNOWN_CHECKER_CODES = CHECKER_CODES_TEXT.split(/\s+/).filter(Boolean);

const STANDARD_CODE_RE = /\b(?:RUN_MSG_[A-Z]+_\d+|DEP_MSG_[A-Z]+_\d+|CHK_MSG_[A-Z_0-9]+)\b/;

const clone_definition = (definition = {}, overrides = {}) => ({
  ...definition,
  ...overrides,
  causes: [...(overrides.causes || definition.causes || [])],
  resolution_steps: [...(overrides.resolution_steps || definition.resolution_steps || [])],
  legacy_patterns: [...(overrides.legacy_patterns || definition.legacy_patterns || [])],
  related_codes: [...(overrides.related_codes || definition.related_codes || [])],
});

const normalize_severity = (type, fallback = 'error') => {
  if (!type) return fallback;
  if (typeof type !== 'string') return fallback;
  const normalized = type.toUpperCase();
  if (normalized === 'W' || normalized === 'WARNING') return 'warning';
  if (normalized === 'I' || normalized === 'INFO') return 'info';
  return 'error';
};

const build_help_slug = (code, fallback) => fallback || code.toLowerCase().replace(/_/g, '-');

const CHECKER_FAMILY_DEFINITIONS = [
  {
    prefix: 'CHK_MSG_GEN_',
    title: 'Studio Checker General Validation Error',
    domain: 'checker',
    category: 'general',
    summary: 'The Studio checker found a general validation problem while inspecting a program.',
    causes: ['The checker encountered malformed workflow or unsupported validation input.', 'The inspected document contains inconsistent or incomplete metadata.'],
    resolution_steps: ['Open the referenced program or workflow item in Studio.', 'Re-save the affected object so Studio rewrites its structure.', 'If the issue is internal checker traversal, inspect the referenced workflow or UI tree for malformed nodes.'],
    help_slug_base: 'studio-checker-general',
  },
  {
    prefix: 'CHK_MSG_OBJ_GEN_',
    title: 'Studio Document Structure Validation Error',
    domain: 'checker',
    category: 'document',
    summary: 'The Studio checker found an invalid top-level document structure, property, or collection shape.',
    causes: ['Required document metadata is missing.', 'An object or array property has the wrong type.', 'IDs or field definitions are duplicated or malformed.'],
    resolution_steps: ['Confirm the document has valid `_id`, `properties`, `studio_meta`, and typed collections.', 'Fix missing or invalid fields in the document payload.', 'Re-save or migrate the object from Studio if the JSON was hand-edited or partially imported.'],
    help_slug_base: 'studio-checker-document',
  },
  {
    prefix: 'CHK_MSG_TBL_GEN_',
    title: 'Table Validation Error',
    domain: 'checker',
    category: 'table',
    summary: 'The checker found a structural problem in a table definition.',
    causes: ['The table is empty or missing required sections.', 'The table is not valid for runtime use.', 'Table metadata or structure was partially deleted or corrupted.'],
    resolution_steps: ['Open the table in Studio and verify fields and indexes exist.', 'Recreate missing table metadata if the object was imported manually.', 'Save the table again after fixing required properties.'],
    help_slug_base: 'studio-checker-table',
  },
  {
    prefix: 'CHK_MSG_TBL_FLD_',
    title: 'Table Field Validation Error',
    domain: 'checker',
    category: 'table-field',
    summary: 'The checker found an invalid field definition inside a table.',
    causes: ['A field is duplicated, malformed, or has an invalid type.', 'A field references a missing model or mask definition.', 'A field is unused or structurally inconsistent.'],
    resolution_steps: ['Inspect the table field list for duplicates and missing properties.', 'Match field types and masks to valid table definitions.', 'Remove or repair broken fields, then save the table.'],
    help_slug_base: 'studio-checker-table-field',
  },
  {
    prefix: 'CHK_MSG_TBL_IDX_',
    title: 'Table Index Validation Error',
    domain: 'checker',
    category: 'table-index',
    summary: 'The checker found an invalid table index configuration.',
    causes: ['The index is empty or has invalid keys.', 'The index name is malformed.', 'The index references fields that do not exist in the table.'],
    resolution_steps: ['Open the table indexes section and verify each index has valid keys.', 'Rename malformed indexes and remove invalid keys.', 'Ensure every index field exists in the table field repository.'],
    help_slug_base: 'studio-checker-table-index',
  },
  {
    prefix: 'CHK_MSG_PRG_COM_',
    title: 'Component Validation Error',
    domain: 'checker',
    category: 'component',
    summary: 'The checker found an invalid component program structure or missing program content.',
    causes: ['The component is missing required UI content.', 'The component references invalid child structures.', 'The component metadata does not match its runtime shape.'],
    resolution_steps: ['Open the component in Studio and confirm its UI tree is valid.', 'Repair missing or empty component sections.', 'Save the component again after fixing its layout or metadata.'],
    help_slug_base: 'studio-checker-component',
  },
  {
    prefix: 'CHK_MSG_PRG_GUI_',
    title: 'Program UI Validation Error',
    domain: 'checker',
    category: 'ui',
    summary: 'The checker found an invalid UI node, attribute, or UI reference inside a program.',
    causes: ['A UI node is malformed or missing required properties.', 'A referenced field or UI binding does not exist.', 'The UI tree contains unsupported shapes or broken references.'],
    resolution_steps: ['Inspect the UI tree around the referenced node.', 'Repair missing `id`, `tagName`, field bindings, or event hooks.', 'Re-save the component after fixing broken UI references.'],
    help_slug_base: 'studio-checker-ui',
  },
  {
    prefix: 'CHK_MSG_PRG_ART_',
    title: 'Alert Program Validation Error',
    domain: 'checker',
    category: 'alert',
    summary: 'The checker found an invalid alert program configuration.',
    causes: ['Alert display or payload settings are incomplete.', 'The alert configuration does not match expected runtime fields.', 'An alert workflow contains missing values.'],
    resolution_steps: ['Open the alert object and confirm display mode, message, and log settings.', 'Fill in missing alert properties.', 'Save the alert again after fixing invalid fields.'],
    help_slug_base: 'studio-checker-alert',
  },
  {
    prefix: 'CHK_MSG_PRG_AGN_',
    title: 'AI Agent Validation Error',
    domain: 'checker',
    category: 'ai-agent',
    summary: 'The checker found an invalid AI agent configuration.',
    causes: ['Required AI agent settings or prompts are missing.', 'The AI agent references invalid dependencies.', 'Agent metadata is incomplete or malformed.'],
    resolution_steps: ['Open the AI agent configuration and verify required fields.', 'Check linked prompts, tools, and dependencies.', 'Save the AI agent again after correcting invalid settings.'],
    help_slug_base: 'studio-checker-ai-agent',
  },
  {
    prefix: 'CHK_MSG_PRG_DSC_',
    title: 'Program Datasource Validation Error',
    domain: 'checker',
    category: 'datasource',
    summary: 'The checker found an invalid datasource definition on a program.',
    causes: ['Datasource type or table reference is missing.', 'Datasource configuration is incomplete.', 'The datasource references invalid indexes or filters.'],
    resolution_steps: ['Inspect the program datasource block in Studio.', 'Set a valid datasource type and required table/index references.', 'Save the program again after fixing datasource settings.'],
    help_slug_base: 'studio-checker-datasource',
  },
  {
    prefix: 'CHK_MSG_PRG_EVT_',
    title: 'Program Event Validation Error',
    domain: 'checker',
    category: 'event',
    summary: 'The checker found a missing or invalid event definition in a program.',
    causes: ['Event references are empty or invalid.', 'Workflow steps refer to missing actions or objects.', 'An event structure is incomplete.'],
    resolution_steps: ['Open the event definition in Studio.', 'Verify the event name, trigger, and workflow steps.', 'Repair missing action or object references, then save.'],
    help_slug_base: 'studio-checker-event',
  },
  {
    prefix: 'CHK_MSG_PRG_EXP_',
    title: 'Expression Validation Error',
    domain: 'checker',
    category: 'expression',
    summary: 'The checker found an invalid expression or expression reference.',
    causes: ['An expression references missing values.', 'Expression syntax is malformed.', 'The expression is incompatible with the expected field type.'],
    resolution_steps: ['Open the expression editor for the referenced field or workflow step.', 'Validate referenced fields and parameters.', 'Fix syntax or cast mismatches, then save the program.'],
    help_slug_base: 'studio-checker-expression',
  },
  {
    prefix: 'CHK_MSG_PRG_FLD_',
    title: 'Program Field Validation Error',
    domain: 'checker',
    category: 'fieldset',
    summary: 'The checker found a broken program field definition or datasource-to-field mismatch.',
    causes: ['A field type is invalid for the program.', 'A table-backed field does not match its datasource.', 'Field metadata is missing, duplicated, or inconsistent.'],
    resolution_steps: ['Inspect the program fieldset in Studio.', 'Match table-backed fields to the datasource table.', 'Repair or remove invalid field definitions, then save the program.'],
    help_slug_base: 'studio-checker-field',
  },
  {
    prefix: 'CHK_MSG_PRG_JVS_',
    title: 'JavaScript Program Validation Error',
    domain: 'checker',
    category: 'javascript',
    summary: 'The checker found an invalid JavaScript program configuration.',
    causes: ['The JavaScript program is missing required content.', 'The program metadata does not match the expected JavaScript shape.'],
    resolution_steps: ['Open the JavaScript program and verify its source and properties.', 'Repair missing code or metadata.', 'Save the program again after fixing invalid settings.'],
    help_slug_base: 'studio-checker-javascript',
  },
  {
    prefix: 'CHK_MSG_PRG_PRM_',
    title: 'Program Parameter Validation Error',
    domain: 'checker',
    category: 'parameter',
    summary: 'The checker found a broken input or output parameter definition.',
    causes: ['Parameter direction or type is invalid.', 'A parameter references missing fields or unsupported structures.', 'Parameter metadata is duplicated or incomplete.'],
    resolution_steps: ['Inspect the program parameter list.', 'Repair missing parameter names, directions, or types.', 'Save the program again after fixing parameter definitions.'],
    help_slug_base: 'studio-checker-parameter',
  },
  {
    prefix: 'CHK_MSG_PRG_TRG_',
    title: 'Workflow Trigger Validation Error',
    domain: 'checker',
    category: 'workflow',
    summary: 'The checker found an invalid workflow trigger or workflow action definition.',
    causes: ['A trigger references a missing program, action, or method.', 'Required workflow fields are empty.', 'The trigger contains an invalid workflow shape.'],
    resolution_steps: ['Inspect the referenced workflow step or trigger.', 'Repair missing program, method, URL, or action references.', 'Save the program again after fixing workflow configuration.'],
    help_slug_base: 'studio-checker-trigger',
  },
  {
    prefix: 'CHK_MSG_RTE_MNU_',
    title: 'Route Menu Validation Error',
    domain: 'checker',
    category: 'route',
    summary: 'The checker found an invalid route or route menu structure.',
    causes: ['A route menu entry is missing required values.', 'A route references invalid programs or menu metadata.'],
    resolution_steps: ['Open the route definition in Studio.', 'Verify menu entries and linked program references.', 'Save the route again after fixing missing values.'],
    help_slug_base: 'studio-checker-route',
  },
];

const CHECKER_EXACT_OVERRIDES = {
  CHK_MSG_GEN_900: {
    title: 'Workflow Search Traversal Warning',
    domain: 'checker',
    category: 'general',
    summary: 'The checker could not fully inspect a workflow while searching for program references.',
    causes: ['The workflow contains malformed trigger data.', 'The checker encountered an unexpected runtime shape during traversal.'],
    resolution_steps: ['Inspect the referenced workflow payload for malformed trigger objects.', 'Re-save the affected program so Studio rewrites its workflow structure.', 'If the warning persists, inspect imported or hand-edited workflow JSON.'],
    help_slug: 'studio-checker-workflow-search-warning',
  },
  CHK_MSG_GEN_902: {
    title: 'UI Workflow Search Traversal Warning',
    domain: 'checker',
    category: 'general',
    summary: 'The checker could not fully inspect a UI tree while searching for workflow references.',
    causes: ['The UI tree contains malformed nodes or xu-on payloads.', 'The checker encountered an unexpected UI node structure during traversal.'],
    resolution_steps: ['Inspect the component UI tree around xu-on handlers.', 'Repair malformed UI nodes or event payloads.', 'Re-save the component after correcting broken UI structure.'],
    help_slug: 'studio-checker-ui-search-warning',
  },
  CHK_MSG_PRG_ART_050: {
    title: 'API Output Missing',
    domain: 'checker',
    category: 'api',
    summary: 'An API program is missing `properties.apiOutput`, so `call_project_api` cannot serialize the response correctly at runtime.',
    causes: ['The API doc was created without an output format.', 'A hand-edited or imported API doc lost its `apiOutput` property.'],
    resolution_steps: ['Open the API program in Studio and choose an output format such as `json` or `html`.', 'Re-save the API doc so Studio writes the missing property back into the payload.', 'If the API is generated, update the generator to always set `properties.apiOutput`.'],
    help_slug: 'studio-checker-api-output-missing',
  },
  CHK_MSG_PRG_COM_040: {
    title: 'Form Root Layout Warning',
    domain: 'checker',
    category: 'component',
    summary: 'A component with `renderType: form` should start with `xu-single-view` so the runtime uses the expected form layout wrapper.',
    causes: ['The root node was authored as a plain HTML element.', 'The component was generated with a list/grid shell even though it is marked as a form.'],
    resolution_steps: ['Change the first root UI node to `xu-single-view`.', 'Keep form-style fields and actions nested under that root wrapper.', 'Re-save the component and rerun the checker.'],
    help_slug: 'studio-checker-form-root-layout-warning',
  },
  CHK_MSG_PRG_COM_042: {
    title: 'List/Grid Root Layout Warning',
    domain: 'checker',
    category: 'component',
    summary: 'A list or grid component should start with `xu-multi-view` so the runtime can apply the expected repeating-view shell.',
    causes: ['The component was authored as a plain container instead of a multi-view root.', 'The render type was changed without updating the root tag.'],
    resolution_steps: ['Change the first root UI node to `xu-multi-view` for list or grid screens.', 'Keep record cards, rows, or repeated content inside that root wrapper.', 'Re-save the component and rerun the checker.'],
    help_slug: 'studio-checker-multiview-root-layout-warning',
  },
  CHK_MSG_PRG_COM_050: {
    title: 'Panel Program Missing',
    domain: 'checker',
    category: 'component',
    summary: 'A `xu-panel` node is missing both a static `program` target and a dynamic `xu-exp:prog` target.',
    causes: ['The panel tag was inserted without wiring its child component reference.', 'A generator emitted a panel shell before selecting the target component.'],
    resolution_steps: ['Set `program=\"component_id\"` on the panel for static routing.', 'Or set `xu-exp:prog` if the target component is dynamic.', 'Re-run the checker after the panel target is defined.'],
    help_slug: 'studio-checker-panel-program-missing',
  },
  CHK_MSG_PRG_COM_052: {
    title: 'Panel Program Not Found',
    domain: 'checker',
    category: 'component',
    summary: 'A `xu-panel` references a program id that does not exist in the current app.',
    causes: ['The panel points to a deleted or misspelled component id.', 'A generator invented a component id instead of using a real Studio doc id.'],
    resolution_steps: ['Replace the panel `program` value with an existing component id.', 'If the child component was renamed or recreated, update the panel reference.', 'Re-save the component after repairing the panel target.'],
    help_slug: 'studio-checker-panel-program-not-found',
  },
  CHK_MSG_PRG_COM_054: {
    title: 'Panel Target Type Invalid',
    domain: 'checker',
    category: 'component',
    summary: 'A `xu-panel` must target another component doc, not a table, folder, or other program type.',
    causes: ['The panel points to a real doc id, but that doc is not a component.', 'A generator reused a table or program id where a screen/component id was required.'],
    resolution_steps: ['Point the panel to a component doc id.', 'Create the missing child component first if only data/docs exist today.', 'Re-save the parent component after fixing the target.'],
    help_slug: 'studio-checker-panel-target-type-invalid',
  },
  CHK_MSG_PRG_COM_056: {
    title: 'Panel Parameter Mismatch',
    domain: 'checker',
    category: 'component',
    summary: 'A `xu-panel` passes a static attribute that does not match any declared input parameter on the target component.',
    causes: ['A static panel parameter name is misspelled.', 'The target component input list changed and the panel attributes were not updated.'],
    resolution_steps: ['Compare the panel attribute names to the target component `progParams` with `dir: in`.', 'Rename the panel attribute or add the missing input parameter on the child component.', 'Prefer `xu-exp:param_name` only when the target parameter actually exists.'],
    help_slug: 'studio-checker-panel-parameter-mismatch',
  },
  CHK_MSG_PRG_GUI_260: {
    title: 'Teleport Target Missing',
    domain: 'checker',
    category: 'ui',
    summary: 'A `xu-teleport` node must define either `to` or `xu-exp:to` so the runtime knows where to move its rendered children.',
    causes: ['The teleport tag was authored without a destination selector.', 'A generator emitted a teleport wrapper before choosing its target node.'],
    resolution_steps: ['Set a static `to=\"#target\"` selector on the teleport node.', 'Or use `xu-exp:to` if the destination selector is dynamic.', 'Re-run the checker after the teleport destination is defined.'],
    help_slug: 'studio-checker-teleport-target-missing',
  },
  CHK_MSG_PRG_GUI_262: {
    title: 'Teleport Selector Not Found',
    domain: 'checker',
    category: 'ui',
    summary: 'A static `xu-teleport` selector does not match any element in the same component tree, so the runtime would fail to mount it.',
    causes: ['The target selector is misspelled or points to a removed node.', 'The teleport was authored before its destination node was added to the tree.'],
    resolution_steps: ['Add or restore a matching target element in the same component tree.', 'Fix the `to` selector so it matches the real target node.', 'If the selector is meant to be dynamic, switch to `xu-exp:to`.'],
    help_slug: 'studio-checker-teleport-selector-not-found',
  },
  CHK_MSG_PRG_GUI_264: {
    title: 'Runtime Internal Tag Authored',
    domain: 'checker',
    category: 'ui',
    summary: 'The UI tree contains a runtime-internal `xu-*` tag that should be produced by the engine, not authored directly.',
    causes: ['The component was hand-edited with an internal runtime wrapper.', 'A generator copied rendered runtime DOM back into the authoring tree.'],
    resolution_steps: ['Remove the internal tag from the authoring tree.', 'Use supported authoring tags such as `xu-single-view`, `xu-multi-view`, `xu-panel`, or `xu-teleport` instead.', 'Re-save the component after removing runtime-only markup.'],
    help_slug: 'studio-checker-runtime-internal-tag-authored',
  },
  CHK_MSG_PRG_GUI_266: {
    title: 'Unsupported Xu Tag Authored',
    domain: 'checker',
    category: 'ui',
    summary: 'The component contains an authored `xu-*` tag that is not part of the supported authoring allowlist.',
    causes: ['A generator invented a new `xu-*` tag.', 'Rendered runtime DOM was copied back into authoring JSON.', 'The tag name is misspelled.'],
    resolution_steps: ['Replace the unsupported tag with a supported authoring tag or plain HTML.', 'Check the runtime docs for the allowed authoring tags.', 'Re-run the checker after repairing the UI tree.'],
    help_slug: 'studio-checker-unsupported-xu-tag-authored',
  },
  CHK_MSG_PRG_GUI_268: {
    title: 'Empty Xu-on Wrapper',
    domain: 'checker',
    category: 'ui',
    summary: 'A `xu-on:*` handler wrapper is present but carries no executable workflow or event payload.',
    causes: ['The handler was created and left empty.', 'A generator emitted an empty wrapper shell.', 'Workflow content was deleted without removing the surrounding handler entry.'],
    resolution_steps: ['Add a real workflow or event payload to the wrapper.', 'Or remove the empty wrapper entry if it is unused.', 'Re-save the component after cleaning up the event handler array.'],
    help_slug: 'studio-checker-empty-xu-on-wrapper',
  },
};

const RUNTIME_ERROR_DEFINITIONS = {
  RUN_MSG_GEN_000: {
    code: 'RUN_MSG_GEN_000',
    title: 'Unhandled Runtime Error',
    severity: 'error',
    domain: 'runtime',
    category: 'general',
    summary: 'The runtime hit an unexpected error that did not match a more specific code.',
    causes: ['An exception bubbled out of a runtime code path without a specific classifier.', 'A new failure mode is not yet mapped to a dedicated runtime code.'],
    resolution_steps: ['Inspect the attached stack trace and source context.', 'Check the console or persisted log entry for the originating source and payload.', 'If the same failure repeats, add a dedicated runtime code and targeted resolution.'],
    help_slug: 'runtime-unhandled-error',
    legacy_patterns: ['generic fallback'],
  },
  RUN_MSG_GEN_010: {
    code: 'RUN_MSG_GEN_010',
    title: 'Runtime Bootstrap Input Error',
    severity: 'error',
    domain: 'runtime',
    category: 'bootstrap',
    summary: 'Xuda was initialized with missing or invalid bootstrap arguments.',
    causes: ['The root element was missing or not found.', 'The runtime options object was missing or had the wrong type.', 'The session was missing a required app identifier.'],
    resolution_steps: ['Pass a valid root HTML element or selector to `xuda(...)`.', 'Ensure the options argument is a plain object.', 'Verify `app_id` is present in runtime options or URL parameters before initialization.'],
    help_slug: 'runtime-bootstrap-input-error',
    legacy_patterns: ['Xuda Error - element argument is empty', 'Xuda Error - element not found', 'Xuda Error - opt argument is undefined', 'Xuda Error - opt argument is not an object', 'no app_id found'],
  },
  RUN_MSG_GEN_020: {
    code: 'RUN_MSG_GEN_020',
    title: 'Unhandled Promise Rejection',
    severity: 'error',
    domain: 'runtime',
    category: 'general',
    summary: 'A promise was rejected without a matching `catch`, so the rejection bubbled to the global browser handler.',
    causes: ['An async code path rejected and no caller handled it.', 'A promise was rejected with an empty or weak error payload, making the failure harder to classify.', 'A lower-level runtime helper rejected after losing the original error object.'],
    resolution_steps: ['Inspect the rejection reason and stack in the attached context.', 'Add a local `catch` or `try/catch` around the async call that can fail.', 'Preserve the original error when rejecting promises instead of rejecting with `undefined` or an empty string.'],
    help_slug: 'runtime-unhandled-promise-rejection',
    legacy_patterns: ['window.unhandledrejection', 'Unhandled promise rejection'],
  },
  RUN_MSG_API_010: {
    code: 'RUN_MSG_API_010',
    title: 'Xuda API Missing Identifier',
    severity: 'error',
    domain: 'runtime',
    category: 'api',
    summary: 'A public `xu.*` helper was called without a required field or event identifier.',
    causes: ['`field_id` was empty for a field helper.', '`event_id` was empty for an event helper.'],
    resolution_steps: ['Pass a non-empty field or event identifier to the helper.', 'If the identifier is dynamic, verify the expression resolves before the API call.', 'Guard helper calls when the underlying field or event may not exist.'],
    help_slug: 'runtime-api-missing-identifier',
    legacy_patterns: ['field_id cannot be empty', 'event_id cannot be empty'],
  },
  RUN_MSG_API_020: {
    code: 'RUN_MSG_API_020',
    title: 'Xuda API Field Not Found',
    severity: 'error',
    domain: 'runtime',
    category: 'api',
    summary: 'A public `xu.*` field helper referenced a field that is not present in the current datasource context.',
    causes: ['The requested field id is not part of the active datasource.', 'The wrong datasource context was used for the API call.'],
    resolution_steps: ['Confirm the field exists in the current program fieldset or datasource.', 'Verify the helper is called from the correct screen or datasource scope.', 'If the field is dynamic, ensure the datasource is initialized before the call.'],
    help_slug: 'runtime-api-field-not-found',
    legacy_patterns: ['field not found'],
  },
  RUN_MSG_API_030: {
    code: 'RUN_MSG_API_030',
    title: 'Xuda API Invalid Field Value',
    severity: 'error',
    domain: 'runtime',
    category: 'api',
    summary: 'A public `xu.*` helper was called with an invalid or missing value payload.',
    causes: ['The requested field update value was `undefined`.', 'A caller attempted to set a field before computing the new value.'],
    resolution_steps: ['Pass a defined value to the helper.', 'Guard optional values before writing them into the datasource.', 'If the value is expression-driven, validate the expression result before calling the API.'],
    help_slug: 'runtime-api-invalid-field-value',
    legacy_patterns: ['value cannot be undefined'],
  },
  RUN_MSG_API_040: {
    code: 'RUN_MSG_API_040',
    title: 'Xuda API Event Identifier Missing',
    severity: 'error',
    domain: 'runtime',
    category: 'api',
    summary: 'A public `xu.*` event helper was called without a required event identifier.',
    causes: ['The caller passed an empty event id.', 'A dynamic event id resolved to an empty value.'],
    resolution_steps: ['Pass a non-empty event id to the helper.', 'Ensure dynamic event names resolve before invocation.', 'Add a guard when the event is optional.'],
    help_slug: 'runtime-api-event-id-missing',
    legacy_patterns: ['xu.invokeEvent: event_id cannot be empty'],
  },
  RUN_MSG_API_050: {
    code: 'RUN_MSG_API_050',
    title: 'Xuda API Event Not Found',
    severity: 'error',
    domain: 'runtime',
    category: 'api',
    summary: 'A public `xu.*` event helper referenced an event that could not be found in any active datasource scope.',
    causes: ['The requested event name does not exist.', 'The event exists in a different screen or datasource scope.', 'The event registry was not initialized yet.'],
    resolution_steps: ['Verify the event exists and is spelled correctly.', 'Call the helper from the correct screen or datasource scope.', 'Delay the invocation until the target program has finished initializing.'],
    help_slug: 'runtime-api-event-not-found',
    legacy_patterns: ['event_id not found'],
  },
  RUN_MSG_API_090: {
    code: 'RUN_MSG_API_090',
    title: 'Xuda API Request Failed',
    severity: 'error',
    domain: 'runtime',
    category: 'api',
    summary: 'A public `xu.*` helper failed while performing an async runtime request.',
    causes: ['A fetch or runtime helper threw an exception.', 'A dependent runtime service was unavailable.', 'The API helper was called with invalid runtime context.'],
    resolution_steps: ['Inspect the attached exception and request parameters.', 'Verify network connectivity and runtime service availability.', 'Check the current session, datasource, and program context for the helper call.'],
    help_slug: 'runtime-api-request-failed',
    legacy_patterns: ['xu.readDrive error', 'xu.writeDrive error', 'xu.callApiProgram error'],
  },
  RUN_MSG_EVT_010: {
    code: 'RUN_MSG_EVT_010',
    title: 'Program Reference Not Found',
    severity: 'error',
    domain: 'runtime',
    category: 'event',
    summary: 'The runtime tried to execute or initialize a program that does not exist or was empty.',
    causes: ['The target program id is wrong or missing.', 'The referenced program was not loaded into the runtime cache.', 'A route or event payload produced an empty program reference.'],
    resolution_steps: ['Verify the referenced program id exists in the project.', 'Check route or event payload expressions that compute the program id.', 'Ensure the program is available in the runtime document cache before invoking it.'],
    help_slug: 'runtime-program-reference-not-found',
    legacy_patterns: ['Program not found', 'Program not exist', 'program is empty', 'program not defined', 'prog empty'],
  },
  RUN_MSG_EVT_020: {
    code: 'RUN_MSG_EVT_020',
    title: 'Invalid On-Load Event Invocation',
    severity: 'error',
    domain: 'runtime',
    category: 'event',
    summary: 'An onscreen event was invoked from an unsupported on-load context.',
    causes: ['A window, modal, or similar onscreen event was triggered during on-load.', 'The event flow used a presentation action in an initialization-only stage.'],
    resolution_steps: ['Move the onscreen action to a user-triggered event or a later lifecycle stage.', 'Avoid opening windows or modal screens directly from on-load handlers.'],
    help_slug: 'runtime-invalid-on-load-event',
    legacy_patterns: ['onscreen (window,modal etc..) event cannot be invoked by on_load'],
  },
  RUN_MSG_EVT_030: {
    code: 'RUN_MSG_EVT_030',
    title: 'Pending URL Event Payload Incomplete',
    severity: 'warning',
    domain: 'runtime',
    category: 'event',
    summary: 'A pending URL event could not be resolved because the URL payload was missing required values.',
    causes: ['The pending event URL was empty.', 'The pending event did not contain a target program id.'],
    resolution_steps: ['Inspect the pending URL event payload and confirm `prog` is present.', 'Avoid enqueueing empty pending URL events.', 'Validate URL-derived parameters before invoking the event flow.'],
    help_slug: 'runtime-pending-url-event-incomplete',
    legacy_patterns: ['url empty', 'prog empty'],
  },
  RUN_MSG_EVT_060: {
    code: 'RUN_MSG_EVT_060',
    title: 'User Event Identifier Missing Or Unknown',
    severity: 'warning',
    domain: 'runtime',
    category: 'event',
    summary: 'A user-defined event could not be invoked because the event identifier was missing or not found.',
    causes: ['The event id parameter was empty.', 'No active datasource contained the requested user-defined event.'],
    resolution_steps: ['Pass a valid event identifier.', 'Verify the event exists in one of the active programs.', 'Invoke the event only after the target screen is mounted.'],
    help_slug: 'runtime-user-event-missing-or-unknown',
    legacy_patterns: ['event_id Cannot be empty', 'event_id not found'],
  },
  RUN_MSG_GUI_010: {
    code: 'RUN_MSG_GUI_010',
    title: 'Teleport Target Container Not Found',
    severity: 'error',
    domain: 'runtime',
    category: 'ui',
    summary: 'A `xu-teleport` node referenced a target container that does not exist in the document.',
    causes: ['The selector in `to` does not match any element.', 'The target container is created after teleport rendering starts.'],
    resolution_steps: ['Verify the teleport selector matches an element that already exists.', 'Render the target container before the teleport content.', 'Avoid using transient or debug-only selectors for teleport targets.'],
    help_slug: 'runtime-teleport-target-missing',
    legacy_patterns: ['for xuTeleportData not found'],
  },
  RUN_MSG_GUI_020: {
    code: 'RUN_MSG_GUI_020',
    title: 'UI Framework Setup Load Failed',
    severity: 'warning',
    domain: 'runtime',
    category: 'ui',
    summary: 'The runtime could not load optional UI framework setup resources.',
    causes: ['The plugin setup module is missing.', 'The plugin setup import failed due to a packaging problem.', 'The current environment cannot resolve the optional setup resource.'],
    resolution_steps: ['Confirm the UI framework plugin exposes its optional setup entry correctly.', 'Verify the plugin package contains the expected setup resource.', 'If the setup module is optional, confirm the runtime can continue without it.'],
    help_slug: 'runtime-ui-framework-setup-load-failed',
    legacy_patterns: ['plugin setup import failed'],
  },
  RUN_MSG_RND_010: {
    code: 'RUN_MSG_RND_010',
    title: 'Invalid xu-on Workflow Syntax',
    severity: 'error',
    domain: 'runtime',
    category: 'render',
    summary: 'The runtime could not parse a `xu-on:*` workflow payload.',
    causes: ['The attribute payload is not valid JSON5.', 'The encoded workflow value contains malformed syntax.', 'The workflow was stringified incorrectly during import or authoring.'],
    resolution_steps: ['Inspect the `xu-on:*` attribute value.', 'Fix JSON5 syntax or encoding issues in the workflow payload.', 'If the payload was imported, re-export it in valid Xuda workflow format.'],
    help_slug: 'runtime-invalid-xu-on-workflow',
    legacy_patterns: ['xu-on has invalid workflow syntax'],
  },
  RUN_MSG_RND_020: {
    code: 'RUN_MSG_RND_020',
    title: 'Slim Mode Screen Type Unsupported',
    severity: 'error',
    domain: 'runtime',
    category: 'render',
    summary: 'Slim mode tried to render a screen type that requires a UI framework plugin.',
    causes: ['Modal, popover, or page rendering was requested in slim mode without a UI framework plugin.', 'The runtime entered a presentation path that slim mode cannot satisfy.'],
    resolution_steps: ['Install and initialize a compatible UI framework plugin.', 'Avoid modal/popover/page presentation flows in slim mode.', 'Switch to a full runtime mode when framework presentation is required.'],
    help_slug: 'runtime-slim-mode-screen-unsupported',
    legacy_patterns: ['Slim mode does not support'],
  },
  RUN_MSG_RND_030: {
    code: 'RUN_MSG_RND_030',
    title: 'Invalid Screen Entry',
    severity: 'error',
    domain: 'runtime',
    category: 'render',
    summary: 'The runtime tried to initialize a screen with an empty or invalid screen object.',
    causes: ['The target program id was empty.', 'The referenced program is not a screen program.', 'A screen initialization flow received the wrong program metadata.'],
    resolution_steps: ['Verify the target screen program id before initialization.', 'Ensure the referenced program is a valid screen object.', 'Inspect route, event, or panel payloads that computed the screen reference.'],
    help_slug: 'runtime-invalid-screen-entry',
    legacy_patterns: ['program is empty', 'program is not a screen object'],
  },
  RUN_MSG_RND_040: {
    code: 'RUN_MSG_RND_040',
    title: 'Empty UI Node Selection',
    severity: 'warning',
    domain: 'runtime',
    category: 'render',
    summary: 'The runtime attempted to render or refresh a UI node selection that resolved to no live nodes.',
    causes: ['The target node was removed before refresh.', 'The selection key no longer points to a live UI node.', 'The render path ran before the live DOM node existed.'],
    resolution_steps: ['Inspect the calling render or refresh path.', 'Ensure the node exists before trying to mutate or refresh it.', 'Check whether the underlying screen was already cleaned or replaced.'],
    help_slug: 'runtime-empty-ui-node-selection',
    legacy_patterns: ['ui node empty'],
  },
  RUN_MSG_RND_050: {
    code: 'RUN_MSG_RND_050',
    title: 'Screen Ready Deadlock',
    severity: 'warning',
    domain: 'runtime',
    category: 'render',
    summary: 'The screen-ready lifecycle stalled while waiting for the rendered UI to become discoverable.',
    causes: ['The screen root was detached or replaced before ready events ran.', 'A render loop or cleanup race prevented the ready target from being found.'],
    resolution_steps: ['Inspect screen-ready lifecycle hooks and cleanup races.', 'Verify the screen root survives until ready events execute.', 'Check recent rendering changes around root replacement or async child mounting.'],
    help_slug: 'runtime-screen-ready-deadlock',
    legacy_patterns: ['deadlock detected for screen ready'],
  },
  RUN_MSG_RND_060: {
    code: 'RUN_MSG_RND_060',
    title: 'Unknown xu Directive',
    severity: 'error',
    domain: 'runtime',
    category: 'render',
    summary: 'The runtime encountered an unknown `xu-*` directive during attribute execution.',
    causes: ['The directive name is misspelled.', 'The relevant runtime handler bundle is missing.', 'A generated document used a directive that is not supported by the current runtime build.'],
    resolution_steps: ['Verify the directive name and spelling.', 'Check that the runtime build includes the expected handler module.', 'Regenerate the document if it was produced by a newer authoring tool than the current runtime.'],
    help_slug: 'runtime-unknown-xu-directive',
    legacy_patterns: ['Unknown xu directive'],
  },
  RUN_MSG_RND_070: {
    code: 'RUN_MSG_RND_070',
    title: 'Realtime Refresh Failed',
    severity: 'warning',
    domain: 'runtime',
    category: 'render',
    summary: 'The runtime failed to refresh a realtime-bound screen after a document change.',
    causes: ['A refresh action threw inside realtime update orchestration.', 'The target datasource or screen state was no longer valid.', 'A panel or screen refresh raced with cleanup.'],
    resolution_steps: ['Inspect the realtime datasource and the affected screen state.', 'Confirm the datasource is still mounted when realtime changes arrive.', 'Check the attached exception for the refresh action that failed.'],
    help_slug: 'runtime-realtime-refresh-failed',
    legacy_patterns: ['realtime refresh failed'],
  },
  RUN_MSG_DSC_010: {
    code: 'RUN_MSG_DSC_010',
    title: 'Datasource Missing',
    severity: 'error',
    domain: 'runtime',
    category: 'datasource',
    summary: 'A runtime operation referenced a datasource session that does not exist.',
    causes: ['The datasource session id is wrong or stale.', 'The datasource was cleaned before the operation ran.', 'The caller used the wrong datasource scope.'],
    resolution_steps: ['Verify the datasource session exists before using it.', 'Check cleanup timing around modals, panels, or screen transitions.', 'Pass the correct datasource session to field and event helpers.'],
    help_slug: 'runtime-datasource-missing',
    legacy_patterns: ['Datasource not exist:', 'Missing datasource:'],
  },
  RUN_MSG_DSC_020: {
    code: 'RUN_MSG_DSC_020',
    title: 'Datasource Table Reference Missing',
    severity: 'error',
    domain: 'runtime',
    category: 'datasource',
    summary: 'A table-backed datasource or field was used without a `dataSourceTableId` reference.',
    causes: ['The program fieldset contains `type: "table"` fields but no datasource table id.', 'The datasource configuration was partially removed or never defined.'],
    resolution_steps: ['Set a valid `progDataSource.dataSourceTableId` on the program.', 'If the field is not table-backed, change the field type to the correct non-table type.', 'Re-save the program after fixing datasource metadata.'],
    help_slug: 'runtime-datasource-table-id-missing',
    legacy_patterns: ['Table type defined without dataSourceTableId deceleration'],
  },
  RUN_MSG_DSC_030: {
    code: 'RUN_MSG_DSC_030',
    title: 'Datasource Table Not Found',
    severity: 'error',
    domain: 'runtime',
    category: 'datasource',
    summary: 'A datasource referenced a table that could not be found or resolved.',
    causes: ['The referenced table id does not exist.', 'The table was removed or not loaded into the runtime cache.', 'The datasource references a stale table id.'],
    resolution_steps: ['Verify the table exists and the referenced id is correct.', 'Ensure the table document is loaded into the runtime context.', 'Update the datasource to point to the correct table id.'],
    help_slug: 'runtime-datasource-table-not-found',
    legacy_patterns: ['Table not found:', 'dataSourceTableId reference error'],
  },
  RUN_MSG_DSC_040: {
    code: 'RUN_MSG_DSC_040',
    title: 'Datasource Row Or Feed Missing',
    severity: 'error',
    domain: 'runtime',
    category: 'datasource',
    summary: 'A datasource operation expected a row or data feed that was not available.',
    causes: ['The requested row id does not exist.', 'The datasource data feed was not initialized.', 'The current record pointer is stale.'],
    resolution_steps: ['Verify the current record id exists in the datasource rows.', 'Ensure the datasource is initialized before reading row values.', 'Refresh or rebuild the datasource when record pointers become stale.'],
    help_slug: 'runtime-datasource-row-or-feed-missing',
    legacy_patterns: ['_raw_data_rows not found', 'ROWID', 'data_feed not found', 'data_feed rows is empty'],
  },
  RUN_MSG_DSC_050: {
    code: 'RUN_MSG_DSC_050',
    title: 'Datasource Deadlock Detected',
    severity: 'warning',
    domain: 'runtime',
    category: 'datasource',
    summary: 'A datasource flow detected a likely deadlock or stalled update path.',
    causes: ['Two datasource operations are waiting on one another.', 'A refresh or lock state was never cleared.', 'A repeated async update loop stalled the datasource.'],
    resolution_steps: ['Inspect the datasource update path and lock lifecycle.', 'Check nested refresh or save flows for re-entry.', 'Clear or redesign stale locking logic around datasource mutation.'],
    help_slug: 'runtime-datasource-deadlock',
    legacy_patterns: ['deadlock detected'],
  },
  RUN_MSG_DSC_060: {
    code: 'RUN_MSG_DSC_060',
    title: 'Datasource Field Lookup Invalid',
    severity: 'warning',
    domain: 'runtime',
    category: 'datasource',
    summary: 'A datasource field lookup failed because the field id or lookup context was invalid.',
    causes: ['The field id type is invalid.', 'A datasource row lookup failed and fell back to parameter search.', 'The datasource lookup context is incomplete.'],
    resolution_steps: ['Pass a string field id to datasource helpers.', 'Verify the active datasource record exists before reading the field.', 'Inspect fallback-to-parameter cases that should have resolved in the datasource.'],
    help_slug: 'runtime-datasource-field-lookup-invalid',
    legacy_patterns: ['Invalid field id type:', 'Datasource row lookup failed'],
  },
  RUN_MSG_EXP_010: {
    code: 'RUN_MSG_EXP_010',
    title: 'Expression Or VM Execution Failed',
    severity: 'error',
    domain: 'runtime',
    category: 'expression',
    summary: 'The runtime could not execute an expression, eval payload, or sandboxed JavaScript block.',
    causes: ['The expression syntax is invalid.', 'The sandboxed script threw an exception.', 'Referenced variables or helpers were missing at execution time.'],
    resolution_steps: ['Inspect the failing expression or JavaScript payload.', 'Verify referenced variables and helpers exist in the current execution scope.', 'Fix syntax or runtime assumptions before re-running the expression.'],
    help_slug: 'runtime-expression-execution-failed',
    legacy_patterns: ['Execution error:', 'vm error', 'Failed to execute script.', 'Asynchronous error caught.'],
  },
  RUN_MSG_DB_010: {
    code: 'RUN_MSG_DB_010',
    title: 'Replication Failed',
    severity: 'error',
    domain: 'runtime',
    category: 'database',
    summary: 'A database replication or change feed operation failed.',
    causes: ['The remote database or websocket endpoint is unavailable.', 'Replication credentials or headers are invalid.', 'A replication callback threw during change handling.'],
    resolution_steps: ['Inspect the replication error payload and remote endpoint reachability.', 'Verify authentication headers and database selection.', 'Check replication callbacks for thrown exceptions during change handling.'],
    help_slug: 'runtime-replication-failed',
    legacy_patterns: ['replication from error'],
  },
  RUN_MSG_DB_020: {
    code: 'RUN_MSG_DB_020',
    title: 'Datasource Feed Empty',
    severity: 'error',
    domain: 'runtime',
    category: 'database',
    summary: 'A database-backed datasource operation expected rows but the feed was empty.',
    causes: ['The underlying query returned no rows when rows were mandatory.', 'The datasource was initialized without expected replication data.', 'The wrong table or index was targeted.'],
    resolution_steps: ['Inspect the datasource query and table id.', 'Verify the datasource was populated before the operation ran.', 'Handle empty feeds explicitly when no rows are a valid state.'],
    help_slug: 'runtime-datasource-feed-empty',
    legacy_patterns: ['data_feed rows is empty'],
  },
  RUN_MSG_WRK_010: {
    code: 'RUN_MSG_WRK_010',
    title: 'Worker Busy Threshold Exceeded',
    severity: 'warning',
    domain: 'runtime',
    category: 'worker',
    summary: 'A runtime worker stayed busy longer than the configured threshold.',
    causes: ['A worker job is stalled or long-running.', 'The worker is blocked on an unresponsive dependency.', 'Too many heavy jobs were scheduled concurrently.'],
    resolution_steps: ['Inspect pending worker jobs and long-running tasks.', 'Profile the worker path for blocking operations.', 'Split or defer heavy jobs if the worker remains saturated.'],
    help_slug: 'runtime-worker-busy-threshold',
    legacy_patterns: ['worker processing more then 10 second'],
  },
  RUN_MSG_WRK_020: {
    code: 'RUN_MSG_WRK_020',
    title: 'Worker Not Responding',
    severity: 'error',
    domain: 'runtime',
    category: 'worker',
    summary: 'A runtime worker stopped responding and the runtime requested a reset.',
    causes: ['The worker deadlocked or crashed.', 'A message callback never completed.', 'A worker-side exception left the job queue in a broken state.'],
    resolution_steps: ['Inspect pending jobs and recent worker exceptions.', 'Review worker reset timing and message flow.', 'Restart or recreate the worker after fixing the blocking path.'],
    help_slug: 'runtime-worker-not-responding',
    legacy_patterns: ['worker not responding'],
  },
  RUN_MSG_WRK_030: {
    code: 'RUN_MSG_WRK_030',
    title: 'Worker Job Missing',
    severity: 'warning',
    domain: 'runtime',
    category: 'worker',
    summary: 'A worker callback or completion path referenced a job that no longer exists.',
    causes: ['The job was already cleaned up.', 'The worker emitted a stale callback.', 'Job lifecycle and cleanup are out of sync.'],
    resolution_steps: ['Inspect worker job creation and cleanup timing.', 'Verify callbacks are not emitted after a job is deleted.', 'Add guards where async worker flows outlive their job records.'],
    help_slug: 'runtime-worker-job-missing',
    legacy_patterns: ['worker job not found'],
  },
  RUN_MSG_WRK_040: {
    code: 'RUN_MSG_WRK_040',
    title: 'Worker Screen Ready Deadlock',
    severity: 'warning',
    domain: 'runtime',
    category: 'worker',
    summary: 'A worker-assisted screen-ready flow stalled before completing.',
    causes: ['The ready event target could not be resolved.', 'A worker lifecycle race blocked the ready completion path.', 'The screen was cleaned before the ready sequence finished.'],
    resolution_steps: ['Inspect the screen-ready and worker interaction path.', 'Check for cleanup or navigation races around mount completion.', 'Ensure ready events run only after the target screen is fully mounted.'],
    help_slug: 'runtime-worker-screen-ready-deadlock',
    legacy_patterns: ['deadlock detected for screen ready'],
  },
  RUN_MSG_NET_010: {
    code: 'RUN_MSG_NET_010',
    title: 'Runtime Resource Load Failed',
    severity: 'warning',
    domain: 'runtime',
    category: 'network',
    summary: 'The runtime could not load an external resource such as a CDN asset or plugin file.',
    causes: ['The URL is wrong or unavailable.', 'The resource format is invalid.', 'The network request failed in the current environment.'],
    resolution_steps: ['Verify the resource URL and response status.', 'Confirm the file format matches the expected runtime loader.', 'Retry in an environment with network access or bundle the resource locally.'],
    help_slug: 'runtime-resource-load-failed',
    legacy_patterns: ['Fail to load:', 'cdn resource in wrong format'],
  },
};

const DEPLOYMENT_ERROR_DEFINITIONS = {
  DEP_MSG_GEN_000: {
    code: 'DEP_MSG_GEN_000',
    title: 'Deployment Server Error',
    severity: 'error',
    domain: 'deployment',
    category: 'general',
    summary: 'The deployment server reported an unexpected error.',
    causes: ['An unhandled exception occurred in the deployment process.', 'A deployment service dependency returned an unexpected failure.', 'A deployment request reached an unsupported or inconsistent state.'],
    resolution_steps: ['Inspect the deployment server stack trace and request context.', 'Verify the deployment build, app configuration, and recent server changes.', 'Retry the failing request after confirming the deployment process is healthy.'],
    help_slug: 'deployment-server-error',
    legacy_patterns: ['Unhandled deployment exception', 'Unhandled deployment rejection'],
  },
  DEP_MSG_CFG_010: {
    code: 'DEP_MSG_CFG_010',
    title: 'Deployment Configuration Mismatch',
    severity: 'error',
    domain: 'deployment',
    category: 'configuration',
    summary: 'The deployment runtime detected missing or inconsistent deployment configuration.',
    causes: ['The requested app id is missing.', 'The loaded deployment config does not match the active app id.', 'The deployment process started with the wrong config payload.'],
    resolution_steps: ['Verify the deployment process booted with the correct app id.', 'Check the deployment config and environment variables used by the process.', 'Redeploy or restart the process with the matching deployment configuration.'],
    help_slug: 'deployment-configuration-mismatch',
    legacy_patterns: ['get_app_id', 'get_app_id not match to', 'get_project_app_id'],
  },
  DEP_MSG_CCH_010: {
    code: 'DEP_MSG_CCH_010',
    title: 'Deployment Couch Connection Failed',
    severity: 'error',
    domain: 'deployment',
    category: 'database',
    summary: 'The deployment process could not resolve or connect to the correct CouchDB database.',
    causes: ['The target app or datacenter document could not be loaded.', 'Deployment database credentials or endpoints are invalid.', 'The database service is unavailable from the deployment host.'],
    resolution_steps: ['Verify the deployment app and datacenter documents exist.', 'Check the generated CouchDB connection settings for the deployment.', 'Confirm network connectivity from the deployment server to CouchDB.'],
    help_slug: 'deployment-couch-connection-failed',
    legacy_patterns: ['get_couch error'],
  },
  DEP_MSG_DPL_010: {
    code: 'DEP_MSG_DPL_010',
    title: 'Deployed Program Build Entry Missing',
    severity: 'error',
    domain: 'deployment',
    category: 'deployment',
    summary: 'The deployment build did not contain the requested program or route document entry.',
    causes: ['The build view is missing the requested program id.', 'The deployment is serving an outdated or incomplete build.', 'The requested program was removed or not deployed.'],
    resolution_steps: ['Confirm the requested program id exists in the current deployment build.', 'Rebuild and redeploy the app if the build index is stale or incomplete.', 'Verify the route or API request points to a deployed program id.'],
    help_slug: 'deployment-program-build-entry-missing',
    legacy_patterns: ['error - view_id not found'],
  },
  DEP_MSG_DPL_020: {
    code: 'DEP_MSG_DPL_020',
    title: 'Deployment Session Expired',
    severity: 'warning',
    domain: 'deployment',
    category: 'session',
    summary: 'The deployment request referenced an expired or invalid session token.',
    causes: ['The app token is expired.', 'The requested session was already closed.', 'The client is using a stale session id.'],
    resolution_steps: ['Create a fresh session token before retrying the request.', 'Ensure the client refreshes expired deployment sessions.', 'Check whether session cleanup is expiring tokens too aggressively.'],
    help_slug: 'deployment-session-expired',
    legacy_patterns: ['session expired'],
  },
  DEP_MSG_DPL_030: {
    code: 'DEP_MSG_DPL_030',
    title: 'Deployment Route File Load Failed',
    severity: 'error',
    domain: 'deployment',
    category: 'routing',
    summary: 'The deployment server could not load or parse a router definition file.',
    causes: ['The route file is missing from the deployment filesystem.', 'The route JSON is malformed.', 'The deployment is pointing to the wrong route document id.'],
    resolution_steps: ['Verify the route file exists in the deployed filesystem.', 'Validate the route document JSON.', 'Redeploy the router build if the route document was not published correctly.'],
    help_slug: 'deployment-route-file-load-failed',
    legacy_patterns: ['Error loading route file:'],
  },
  DEP_MSG_NET_010: {
    code: 'DEP_MSG_NET_010',
    title: 'Deployment Network Request Failed',
    severity: 'error',
    domain: 'deployment',
    category: 'network',
    summary: 'The deployment server failed to complete an outbound HTTP request needed for app execution.',
    causes: ['The upstream endpoint returned an error status.', 'The deployment host could not reach the upstream service.', 'The response payload was invalid for the expected flow.'],
    resolution_steps: ['Inspect the upstream URL, response status, and payload.', 'Verify outbound connectivity from the deployment host.', 'Retry after confirming the upstream service is healthy.'],
    help_slug: 'deployment-network-request-failed',
    legacy_patterns: ['HTTP error! status:'],
  },
  DEP_MSG_API_010: {
    code: 'DEP_MSG_API_010',
    title: 'Deployment API Program Lookup Failed',
    severity: 'error',
    domain: 'deployment',
    category: 'api',
    summary: 'The deployment server could not resolve the requested API program from the deployed build.',
    causes: ['The program id is missing or invalid.', 'The program was not included in the deployed build.', 'The request targets the wrong deployment.'],
    resolution_steps: ['Verify the requested `prog_id` exists in the deployed build.', 'Check that the API request is being sent to the correct deployment host.', 'Redeploy if the build index is missing the API program.'],
    help_slug: 'deployment-api-program-lookup-failed',
    legacy_patterns: ['Program not exist', 'error - view_id not found'],
  },
  DEP_MSG_API_020: {
    code: 'DEP_MSG_API_020',
    title: 'Unsupported Deployment API Program Type',
    severity: 'error',
    domain: 'deployment',
    category: 'api',
    summary: 'A deployment API request targeted a program that is not an API program.',
    causes: ['The requested program is not configured as `menuType: api`.', 'A route or client request points to the wrong program id.', 'Deployment metadata is out of sync with the intended API target.'],
    resolution_steps: ['Point the request to a deployed API program.', 'Verify the target program `menuType` is `api`.', 'Redeploy after correcting the API target program or route configuration.'],
    help_slug: 'deployment-unsupported-api-program-type',
    legacy_patterns: ['is not supported for api job'],
  },
  DEP_MSG_API_030: {
    code: 'DEP_MSG_API_030',
    title: 'Deployment API Execution Failed',
    severity: 'error',
    domain: 'deployment',
    category: 'api',
    summary: 'The deployment server failed while executing a deployed API program.',
    causes: ['The worker execution raised an exception.', 'The API program emitted invalid output for the requested response type.', 'The deployment server hit a runtime failure while preparing the API datasource.'],
    resolution_steps: ['Inspect the deployment worker logs and stack trace.', 'Verify the API program output type matches the rendered output.', 'Retry after confirming the worker and datasource layers are healthy.'],
    help_slug: 'deployment-api-execution-failed',
    legacy_patterns: ['execute_api_program'],
  },
  DEP_MSG_DBS_010: {
    code: 'DEP_MSG_DBS_010',
    title: 'Deployment DB Plugin Execution Failed',
    severity: 'error',
    domain: 'deployment',
    category: 'database',
    summary: 'A deployment-side database plugin or server script failed during execution.',
    causes: ['The DB plugin threw an exception.', 'The VM wrapper rejected or timed out.', 'The plugin script is incompatible with the current deployment environment.'],
    resolution_steps: ['Inspect the DB plugin method and deployment-side stack trace.', 'Verify the plugin script and setup document are valid.', 'Check for timeout, VM sandbox, or dependency issues in the plugin environment.'],
    help_slug: 'deployment-db-plugin-execution-failed',
    legacy_patterns: ['Failed to execute script.', 'Asynchronous error caught.', 'dbs_'],
  },
  DEP_MSG_WRK_010: {
    code: 'DEP_MSG_WRK_010',
    title: 'Deployment Worker Script Failed',
    severity: 'error',
    domain: 'deployment',
    category: 'worker',
    summary: 'The deployment worker failed while running server-side JavaScript.',
    causes: ['The script threw inside the worker VM.', 'The worker process hit an uncaught exception.', 'The script depends on unavailable modules or invalid runtime state.'],
    resolution_steps: ['Inspect the deployment worker stack trace and script body.', 'Verify the worker bundle and dependencies are present on the deployment host.', 'Retry after fixing the server-side script logic or runtime assumptions.'],
    help_slug: 'deployment-worker-script-failed',
    legacy_patterns: ['vm error', 'Failed to execute script.', 'Asynchronous error caught.'],
  },
  DEP_MSG_SEC_010: {
    code: 'DEP_MSG_SEC_010',
    title: 'Deployment Program Access Denied',
    severity: 'error',
    domain: 'deployment',
    category: 'security',
    summary: 'The deployment rejected a program-level request because the target program is invalid or unauthorized.',
    causes: ['The request omitted `prog_id`.', 'The deployment request referenced a program outside the allowed deployment scope.', 'The request program id does not exist in the build context.'],
    resolution_steps: ['Verify the request includes a valid deployed `prog_id`.', 'Check the deployment access lists for allowed programs.', 'Update the deployment scope if the program should be accessible.'],
    help_slug: 'deployment-program-access-denied',
    legacy_patterns: ['invalid or missing prog id', 'prog_id unauthorized'],
  },
  DEP_MSG_SEC_020: {
    code: 'DEP_MSG_SEC_020',
    title: 'Deployment Table Access Denied',
    severity: 'error',
    domain: 'deployment',
    category: 'security',
    summary: 'The deployment rejected a table-level request because the target table is invalid or unauthorized.',
    causes: ['The request omitted `table_id`.', 'The target table is not exposed to the deployment.', 'The program context does not reference the requested table.'],
    resolution_steps: ['Verify the request includes a valid deployed `table_id`.', 'Check the deployment access lists for allowed tables.', 'Ensure the target program actually references the requested table.'],
    help_slug: 'deployment-table-access-denied',
    legacy_patterns: ['invalid or missing table id', 'table_id cannot be authenticate', 'does not exist in the program context'],
  },
};

const RUNTIME_MATCHERS = [
  { code: 'RUN_MSG_GEN_010', test: ({ source = '', message = '' }) => /Xuda Error - element argument is empty|Xuda Error - element not found|Xuda Error - opt argument is undefined|Xuda Error - opt argument is not an object|no app_id found/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_GEN_020', test: ({ source = '', message = '' }) => /window\.unhandledrejection|Unhandled promise rejection/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_API_010', test: ({ source = '', message = '' }) => /field_id cannot be empty|event_id cannot be empty/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_API_020', test: ({ source = '', message = '' }) => /xu\.(getFieldValue|setFieldValue): .* field not found/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_API_030', test: ({ source = '', message = '' }) => /value cannot be undefined/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_API_040', test: ({ source = '', message = '' }) => /xu\.invokeEvent: event_id cannot be empty/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_API_050', test: ({ source = '', message = '' }) => /event_id not found/i.test(`${source} ${message}`) && /xu\.invokeEvent|xu\.invokeEvent error/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_API_090', test: ({ source = '', message = '' }) => /xu\..* error/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_EVT_020', test: ({ source = '', message = '' }) => /onscreen \(window,modal etc\.\) event cannot be invoked by on_load/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_EVT_060', test: ({ source = '', message = '' }) => /event_id Cannot be empty|event_id not found/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_EVT_030', test: ({ source = '', message = '' }) => /\burl empty\b|\bprog empty\b/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_EVT_010', test: ({ source = '', message = '' }) => /Program not found|Program not exist|program not defined|program is empty/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_GUI_010', test: ({ source = '', message = '' }) => /xuTeleportData not found/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_GUI_020', test: ({ source = '', message = '' }) => /plugin setup import failed|plugin .* not found|plugin .* is empty|plugin core not found/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_RND_010', test: ({ source = '', message = '' }) => /xu-on has invalid workflow syntax/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_RND_020', test: ({ source = '', message = '' }) => /Slim mode does not support/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_RND_030', test: ({ source = '', message = '' }) => /program is not a screen object/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_RND_040', test: ({ source = '', message = '' }) => /ui node empty/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_RND_050', test: ({ source = '', message = '' }) => /deadlock detected for screen ready/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_RND_060', test: ({ source = '', message = '' }) => /Unknown xu directive/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_RND_070', test: ({ source = '', message = '' }) => /realtime refresh failed/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_DSC_020', test: ({ source = '', message = '' }) => /Table type defined without dataSourceTableId deceleration/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_DSC_030', test: ({ source = '', message = '' }) => /Table not found:|dataSourceTableId reference error/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_DSC_010', test: ({ source = '', message = '' }) => /Datasource not exist:|Missing datasource:/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_DSC_050', test: ({ source = '', message = '' }) => /deadlock detected/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_DSC_060', test: ({ source = '', message = '' }) => /Invalid field id type:|Datasource row lookup failed/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_DSC_040', test: ({ source = '', message = '' }) => /_raw_data_rows not found|ROWID .* not found|data_feed not found|data_feed rows is empty/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_DB_010', test: ({ source = '', message = '' }) => /replication from error/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_DB_020', test: ({ source = '', message = '' }) => /data_feed rows is empty/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_EXP_010', test: ({ source = '', message = '', err }) => /Execution error:|vm error|Failed to execute script\.|Asynchronous error caught\./i.test(`${source} ${message} ${err?.message || ''}`) },
  { code: 'RUN_MSG_WRK_010', test: ({ source = '', message = '' }) => /utils\.worker\.busy|worker processing more then 10 second/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_WRK_020', test: ({ source = '', message = '' }) => /utils\.worker\.reset|worker not responding/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_WRK_030', test: ({ source = '', message = '' }) => /worker job not found/i.test(`${source} ${message}`) },
  { code: 'RUN_MSG_NET_010', test: ({ source = '', message = '' }) => /Fail to load:|cdn resource in wrong format/i.test(`${source} ${message}`) },
];

const DEPLOYMENT_MATCHERS = [
  { code: 'DEP_MSG_CFG_010', test: ({ source = '', message = '' }) => /get_app_id|get_project_app_id/i.test(`${source} ${message}`) },
  { code: 'DEP_MSG_DPL_010', test: ({ source = '', message = '' }) => /error - view_id not found/i.test(`${source} ${message}`) },
  { code: 'DEP_MSG_DPL_020', test: ({ source = '', message = '' }) => /session expired/i.test(`${source} ${message}`) },
  { code: 'DEP_MSG_DPL_030', test: ({ source = '', message = '' }) => /Error loading route file:/i.test(`${source} ${message}`) },
  { code: 'DEP_MSG_NET_010', test: ({ source = '', message = '' }) => /HTTP error! status:|create_app_session/i.test(`${source} ${message}`) },
  { code: 'DEP_MSG_API_020', test: ({ source = '', message = '' }) => /is not supported for api job/i.test(`${source} ${message}`) },
  { code: 'DEP_MSG_DBS_010', test: ({ source = '', message = '' }) => /dbs_|server script|Failed to execute script\.|Asynchronous error caught\./i.test(`${source} ${message}`) },
  { code: 'DEP_MSG_WRK_010', test: ({ source = '', message = '' }) => /vm error|execute_javascript|Failed to execute script\.|Asynchronous error caught\./i.test(`${source} ${message}`) },
  { code: 'DEP_MSG_SEC_010', test: ({ source = '', message = '' }) => /invalid or missing prog id|prog_id unauthorized/i.test(`${source} ${message}`) },
  { code: 'DEP_MSG_SEC_020', test: ({ source = '', message = '' }) => /invalid or missing table id|table_id cannot be authenticate|does not exist in the program context/i.test(`${source} ${message}`) },
];

export const uncovered_reporting_hotspots = [
  {
    id: 'api_library_public_helpers',
    file: 'runtime/js/modules/xuda-api-library.mjs',
    summary: 'Public `xu.*` helpers exposed raw console errors for missing field ids, missing events, and generic async failures.',
  },
  {
    id: 'event_and_screen_entrypoints',
    file: 'runtime/js/xuda_events.js',
    summary: 'Event invocation and pending URL flows emitted raw warnings/errors for empty program, URL, and event ids.',
  },
  {
    id: 'screen_init_entry',
    file: 'runtime/js/xuda_runtime.browser.js',
    summary: 'Screen initialization emitted raw console errors for empty program ids and invalid screen objects.',
  },
  {
    id: 'render_behavior_parsing',
    file: 'runtime/js/xuda_runtime.browser.behavior.js',
    summary: 'Invalid `xu-on` workflow syntax was reported only as raw console errors.',
  },
  {
    id: 'teleport_target_resolution',
    file: 'runtime/js/xuda_runtime.browser.handlers.nodes.js',
    summary: 'Missing teleport target containers aborted rendering without a standard error code.',
  },
  {
    id: 'datasource_expression_replication',
    file: 'runtime/js/xuda_datasource.js',
    summary: 'Datasource deadlocks, row lookup failures, and hidden fallback paths were under-reported or uncoded.',
  },
  {
    id: 'expression_vm_execution',
    file: 'runtime/js/xuda_expression.js',
    summary: 'Expression and sandbox execution failures used raw console logging instead of stable runtime codes.',
  },
  {
    id: 'db_replication_runtime',
    file: 'runtime/js/modules/xuda-db-adapter-module.mjs',
    summary: 'Replication failures and empty data feeds were not mapped to help-site-facing codes.',
  },
  {
    id: 'silent_realtime_refresh_failure',
    file: 'runtime/js/xuda_runtime.browser.realtime.js',
    summary: 'Realtime refresh catches swallowed errors without leaving a traceable runtime code.',
  },
  {
    id: 'ui_framework_setup_import',
    file: 'runtime/js/xuda_UI.utils.js',
    summary: 'Optional UI framework setup import failures were silently ignored.',
  },
  {
    id: 'checker_console_only_paths',
    file: 'runtime/js/modules/xuda-studio-checker.mjs',
    summary: 'Checker traversal errors still used raw console logging instead of structured checker warnings.',
  },
];

const extract_standard_code = (value) => {
  if (typeof value !== 'string') return null;
  const match = value.match(STANDARD_CODE_RE);
  return match ? match[0] : null;
};

const get_runtime_definition_by_code = (code) => {
  if (!code || !RUNTIME_ERROR_DEFINITIONS[code]) return null;
  const definition = RUNTIME_ERROR_DEFINITIONS[code];
  return clone_definition(definition, {
    code,
    help_slug: build_help_slug(code, definition.help_slug),
  });
};

const get_deployment_definition_by_code = (code) => {
  if (!code || !DEPLOYMENT_ERROR_DEFINITIONS[code]) return null;
  const definition = DEPLOYMENT_ERROR_DEFINITIONS[code];
  return clone_definition(definition, {
    code,
    help_slug: build_help_slug(code, definition.help_slug),
  });
};

const get_checker_family_definition = (code) => CHECKER_FAMILY_DEFINITIONS.find((definition) => code.startsWith(definition.prefix)) || null;

const get_checker_definition_by_code = (code, context = {}) => {
  if (!code || !code.startsWith('CHK_MSG_')) return null;
  const override = CHECKER_EXACT_OVERRIDES[code];
  const family = get_checker_family_definition(code);
  if (!family && !override) return null;

  const definition = clone_definition(family || {}, override || {});
  definition.code = code;
  definition.domain = definition.domain || 'checker';
  definition.category = definition.category || context.category || 'general';
  definition.severity = normalize_severity(context.type, definition.severity || 'error');
  definition.help_slug = build_help_slug(code, definition.help_slug);
  definition.title = definition.title || 'Studio Checker Validation Error';
  definition.summary = definition.summary || 'The Studio checker found a validation issue.';
  definition.family_code = family?.prefix || null;
  return definition;
};

export const is_standard_error_code = (code) => !!get_error_definition(code);

export const get_error_definition = (input, context = {}) => {
  const code = typeof input === 'string' ? extract_standard_code(input) || input : extract_standard_code(input?.code || input?.message || input?.source);
  if (!code) return null;
  return get_runtime_definition_by_code(code) || get_deployment_definition_by_code(code) || get_checker_definition_by_code(code, context);
};

export const classify_runtime_issue = (payload = {}) => {
  const explicit = get_error_definition(payload, payload);
  if (explicit && explicit.code.startsWith('RUN_MSG_')) {
    return explicit;
  }

  for (const matcher of RUNTIME_MATCHERS) {
    if (matcher.test(payload)) {
      return get_runtime_definition_by_code(matcher.code);
    }
  }

  return get_runtime_definition_by_code('RUN_MSG_GEN_000');
};

export const get_runtime_report_definition = (payload = {}) => {
  const definition = classify_runtime_issue(payload);
  return clone_definition(definition, {
    severity: normalize_severity(payload.type, definition.severity || 'error'),
  });
};

export const classify_server_issue = (payload = {}) => {
  const explicit = get_error_definition(payload, payload);
  if (explicit && explicit.code.startsWith('DEP_MSG_')) {
    return explicit;
  }

  for (const matcher of DEPLOYMENT_MATCHERS) {
    if (matcher.test(payload)) {
      return get_deployment_definition_by_code(matcher.code);
    }
  }

  return get_deployment_definition_by_code('DEP_MSG_GEN_000');
};

export const get_server_report_definition = (payload = {}) => {
  const definition = classify_server_issue(payload);
  return clone_definition(definition, {
    severity: normalize_severity(payload.type, definition.severity || 'error'),
  });
};

export const list_error_definitions = () => {
  const runtime_definitions = Object.keys(RUNTIME_ERROR_DEFINITIONS)
    .sort()
    .map((code) => get_runtime_definition_by_code(code));

  const deployment_definitions = Object.keys(DEPLOYMENT_ERROR_DEFINITIONS)
    .sort()
    .map((code) => get_deployment_definition_by_code(code));

  const checker_definitions = [...new Set(KNOWN_CHECKER_CODES)]
    .sort()
    .map((code) => get_checker_definition_by_code(code))
    .filter(Boolean);

  return [...runtime_definitions, ...deployment_definitions, ...checker_definitions];
};

export const get_error_catalog_manifest = () => ({
  generated_from: 'runtime/js/modules/xuda-error-registry-module.mjs',
  runtime_definition_count: Object.keys(RUNTIME_ERROR_DEFINITIONS).length,
  deployment_definition_count: Object.keys(DEPLOYMENT_ERROR_DEFINITIONS).length,
  checker_definition_count: [...new Set(KNOWN_CHECKER_CODES)].length,
  total_definition_count:
    Object.keys(RUNTIME_ERROR_DEFINITIONS).length + Object.keys(DEPLOYMENT_ERROR_DEFINITIONS).length + [...new Set(KNOWN_CHECKER_CODES)].length,
  definitions: list_error_definitions(),
});

export const get_uncovered_reporting_audit = () => ({
  snapshot: {
    checker_codes: [...new Set(KNOWN_CHECKER_CODES)].length,
    debug_report_call_sites: 66,
    raw_console_sites: 170,
    throw_sites: 27,
    silent_catch_sites: 19,
  },
  hotspots: uncovered_reporting_hotspots,
});
