builtin/am: introduce write_state_*() helper functions