Add a purpose-field to the context of an event

tl;dr Add another field to the context object:

Field Description
purpose Custom identifier passed through from the corresponding service call.

Currently, an event looks like this (I changed an input_text entity in my Lovelace dashboard):

event_type: state_changed
data:
  entity_id: input_text.test
  old_state:
    entity_id: input_text.test
    state: "123"
    attributes:
      editable: true
      min: 0
      max: 100
      pattern: null
      mode: text
      friendly_name: test
    last_changed: "2024-01-26T10:32:37.592501+00:00"
    last_updated: "2024-01-26T10:32:37.592501+00:00"
    context:
      id: 01HN2N87YRBRXSBGWNNBRM7050
      parent_id: null
      user_id: null
  new_state:
    entity_id: input_text.test
    state: "1234"
    attributes:
      editable: true
      min: 0
      max: 100
      pattern: null
      mode: text
      friendly_name: test
    last_changed: "2024-01-26T10:33:06.920615+00:00"
    last_updated: "2024-01-26T10:33:06.920615+00:00"
    context:
      id: 01HN2N94K8JNG9JYGRVTPQWT1A
      parent_id: null
      user_id: e07234cbc3f24760b38e50ff83dae4f8
origin: LOCAL
time_fired: "2024-01-26T10:33:06.920615+00:00"
context:
  id: 01HN2N94K8JNG9JYGRVTPQWT1A
  parent_id: null
  user_id: e07234cbc3f24760b38e50ff83dae4f8

Let’s look at the context part. The user_id is filled because I changed the value of the text in the UI.

A context object contains the following fields (from: Home Assistant Context | Home Assistant Data Science Portal):

Field Description
context_id Unique identifier for the context.
user_id Unique identifier of the user that started the change.
parent_id Unique identifier of the parent context_id that started the change.

If something is listening to this event, getting more context from it is hard. It would be helpful to add a purpose to the corresponding service call:

service: light.turn_on
target:
  entity_id: light.hue_color_lamp_1
data: {}
purpose: auto_lighting

And the event fired would look like this:

event_type: state_changed
data: {...}
origin: LOCAL
time_fired: "2024-01-26T10:43:06.920615+00:00"
context:
  id: 01HN2N94K8JNG9JYGRVTPQWT1B
  parent_id: null
  user_id: null
  purpose: auto_lighting

Example:
Consider a lighting workflow that monitors state_changed events. In this scenario, the workflow recognizes that if the change in light state is a result of a service call initiated by the same workflow, it should disregard the event. Events lacking the purpose: auto_lighting attribute could be identified as manual changes made outside the automated lighting system.

Indentation here:

service: light.turn_on
target:
  entity_id: light.hue_color_lamp_1
data: {}
purpose: auto_lighting

Should be:

service: light.turn_on
target:
  entity_id: light.hue_color_lamp_1
data: {}
  purpose: auto_lighting